First way to make header file:
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"
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.