How do header and source files in C work?

后端 未结 5 874
北海茫月
北海茫月 2020-11-30 18:07

I\'ve perused the possible duplicates, however none of the answers there are sinking in.

tl;dr: How are source and header files related in C? Do

5条回答
  •  情歌与酒
    2020-11-30 18:46

    The C language has no concept of source files and header files (and neither does the compiler). This is merely a convention; remember that a header file is always #included into a source file; the preprocessor literally just copy-pastes the contents, before proper compilation begins.

    Your example should compile (foolish syntax errors notwithstanding). Using GCC, for example, you might first do:

    gcc -c -o source.o source.c
    gcc -c -o main.o main.c
    

    This compiles each source file separately, creating independent object files. At this stage, returnSeven() has not been resolved inside main.c; the compiler has merely marked the object file in a way that states that it must be resolved in the future. So at this stage, it's not a problem that main.c can't see a definition of returnSeven(). (Note: this is distinct from the fact that main.c must be able to see a declaration of returnSeven() in order to compile; it must know that it is indeed a function, and what its prototype is. That is why you must #include "source.h" in main.c.)

    You then do:

    gcc -o my_prog source.o main.o
    

    This links the two object files together into an executable binary, and performs resolution of symbols. In our example, this is possible, because main.o requires returnSeven(), and this is exposed by source.o. In cases where everything doesn't match up, a linker error would result.

提交回复
热议问题