What is the -o option in GCC? [duplicate]

2020-04-01 08:17发布

问题:

gcc -c x.c

tells the compiler to create the object code from the x.c file, and not try to link it, right?

What does the -o option tell the compiler as in the following?

gcc a.o y.o -o x.out

And the other question I have is, when I have source code like:

#include <stdio.h>

int main(){
    puts("");
}

Well OK, the compiler knows where to look for stdio.h, but the executable must be linked to stdio.o, mustn't it? Where does the stdio.o file reside?

回答1:

See manpages.info/linux/gcc.1.html. Under the Synopsis section, you will see the -o option.

Regarding

Well OK, the compiler knows where to look for stdio.h, but the executable must be linked to stdio.o, mustn't it? Where does the stdio.o file reside?

The answer to the first question is "No". Since the answer to the first question is "No", the second question is not relevant.

The functions and variables declared in stdio.h need not be in stdio.o. They are usually in a library (.a or .so) which are found in one of the directories where the linker looks for library files.

In general, there is no rule that each .h file has a corresponding .o file. It is possible to have the functions and variables declared in a .h file to be implemented in multiple .c files that will result in multiple .o files. It is also possible to have functions and variables declared in multiple .h files to be implemented in one .c file. How these are organized varies from project to project.

Each .c file, on the other hand, has a corresponding .o file (I haven't seen any platforms where multiple .c files can be compiled to create one .o file). All the .o files resulting from compiling the .c files are linked together to create an executable.



回答2:

It indicates the output file, i.e. what your object-file or executable should be. You can see this information by doing gcc --help or man gcc.

<stdio.h> is part of the standard library, which your compiler is already linking to.



回答3:

gcc -o [file]

Writes the build output to an output file. This is not to be confused with -O which is the optimization level. I don't believe this option has anything to do with linking.