简体   繁体   中英

To make a header file, do we need to separate declaration from definition function?

First way to make header file: 头文件、源文件、主文件和执行命令

Second way: 只有头文件和主文件,没有源文件

The first picture is screenshot I took from here . It contains three files: the Header file , the Source file , and the Main file , as well as how to compile them and link the source file to the main file: gcc -o my_app main.c foo.c . I didn't test it, but I assume that it is working fine.

The second picture is when the Header file which the function is declared and defined/implemented in a file named " foo.h " file. The header file then is called in the Main file ( #include "foo.h" ). To compile and run it (in Dev-C++ 6.3 I use), just press F11. Simpler. Indeed, the first way I can execute in Dev-C++ 6.3 without too complicated by calling the "foo.c" in the main file by including the " foo.c " ( #include "foo.c" ). Both way give the same output.

My question is, what is the advantage/disadvantage of the first way and that my way/the second way to make header in C/C++?

hat is the advantage/disadvantage of the first way and that my way/the second way to make header in C/C++?

The second way is problematic. In particular, in the second way if/when the header foo.h is included in more than one source file, we will get a linker error saying:

 multiple definition of `foo()'

because foo() is a non-inline function and so it must be defined only once across the whole program in C++.

To solve, this you can either make use of inline keyword to make foo inline or use way 1 in your question.

foo.h

 #ifndef FOO_H #define FOO_H vvvvvv------------->note the inline inline void foo() { } #endif

main.cpp

#include "foo.h" int main() { foo(); return 0; }

source2.cpp

 #include "foo.h"

Demo with inline keyword

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM