Consider the code.
#ifndef FOO_H
#define FOO_H
//Code
#endif
Code can be following cases
// Case 1:
#define foo 0
// Case 2:
void foo_method(){};
// Case 3:
int foo;
foo.h
is included in many C files. When I compile only the case 1 is without errors, other cases throw errors of duplication.
Why is so when the foo.h
is not concatenated to C files except the one while compiling?
About case 2:
you should only declare the function signature, not the body. it has nothing to do with the pre-processor commands.
in the header file (decleration only)
#if <Condition>
void foo();
#endif
in the C file
#if <Condition>
void foo(){
//body
}
#endif
about case 3:
it's similar to case 2, with the addition that you should declare variables in the header file if they are extern , there is no need to declare them in a header file otherwise. if they are declared as extern, they also need to be declared in a C file without the extern keyword:
in the header file:
#if <Condition>
extern int bar;
#endif
in the C file:
#if <Condition>
int bar;
#endif