Help with a object file

B

bashcommando

Guest
I used gcc on my code and it turned it into a object file. I have no idea why, but how do I make it into a elf program?
 


Usually you use the -o option to specify the name of the executable.
e.g.
Code:
gcc ./main.cpp -o myprogram

If that's not any help to you, post the command you are using to build (or your makefile) and we'll see whats going wrong!
 
I used gcc on my code and it turned it into a object file. I have no idea why, but how do I make it into a elf program?
By default, if you do not use the -o option to name the executable, gcc will create an executable file called a.out, regardless of the name of the .c file. I always use the -o option.

For beginners, I recommend the following command line to compile one or more files:

Code:
gcc -Wall -Wextra -o foo  foo.c  bar.c

See: GCC Options for more information.
 
Last edited:
By default, if you do not use the -o option to name the executable, gcc will create an executable file called a.out, regardless of the name of the .c file. I always use the -o option.

For beginners, I recommend the following command line to compile one or more files:

Code:
gcc -Wall -Wextra -o foo  foo.c  bar.c

See: GCC Options for more information.

Sorry, I was posting from my phone yesterday, so I used the bare minimum to answer the question, otherwise I would have gone into more detail! But yes, the -Wall and -Wextra options are also good to include. Then there is the -g flag for generating debug info. Always handy in the early stages of a programs development, when you are most likely to need to do some debugging. Then remove the -g flag for release builds and add the -O2 optimisation flag!

For a .o file to have been created, I imagine that bashcommando was using the -c option, which will compile the selected module to a .o file and skips/omits the link step, so there will be no a.out.

After compiling your source code to .o files using the -c flag, you can link the .o files together into an executable using gcc like this:
Code:
gcc main.o foo.o bar.o -o programname

So the first object file is the main object, and the subsequent objects are for the modules it depends on. You see this kind of thing in Makefiles. The source files are compiled to .o files and then linked to form the executable in a separate pass:

Code:
MYFILEPATH = ./src/
CC = gcc
CFLAGS = -Wall -Wextra -O2
OBJECTS = main.o foo.o bar.o

programname: $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o programname

main.o: $(MYFILEPATH)main.c
    $(CC) $(CFLAGS) -c $(MYFILEPATH)main.c

foo.o: $(MYFILEPATH)foo.c
    $(CC) $(CFLAGS) -c $(MYFILEPATH)foo.c

bar.o: $(MYFILEPATH)bar.c
    $(CC) $(CFLAGS) -c $(MYFILEPATH)bar.c

clean:
    rm ./programname ./*.o
 


Latest posts

Top