test me test me - 2 months ago 5
C Question

Why I cannot run an object file?

When I want to run a source code why this works :

gcc test.c -o test.o


then

./test.o


but this does not work :

gcc -c test.c


then

./test.o


and get this message

bash: ./test.o: Permission denied

Answer

First of all, you are not creating an object file but an executable file. Object files are an intermediate file used as input file for the linker to create the executable file. That you name it with an .o suffix doesn't matter.

Secondly, due to tradition if you do not specify an output filename with the -o option the compiler frontend program and linker will create an executable named a.out.

But that's not all, because with the second example you are actually creating a real object file, and those are not executable. Like mentioned above, those needs to be passed to a separate linking step to create the executable file.

You either need to create an executable file:

gcc test.c
./a.out

Or you should link the object file into an executable file:

gcc -c test.c            # Create object file
gcc test.o -o test       # Use object file to create executable file
./test                   # Run the executable file
Comments