The included protection used in your final example is to prevent you including a header file twice into a single C file. It wont help across multiple C files.
Your problem is that header files should really only contain declarations, declarations
define data types
declare the existence of variables
declare the existence of functions
However your header file includes a definition, a definition
Provides the body for a function
Causes the compiler to actually allocate storage space for a variable.
Your statement
- struct __solid
-
{
-
char s[100];
-
} solid;
Declares the variable type struct __solid but defines the variable solid. Since you include the header into 2 C files the variable is defined in each of them and when you link you get a symbol defined multiple times error because the linker is unable to know which of the 2 definitions of solid should be used for the program.
You should not be defining data in header files. what you need to do is this, in the header use the statements
- struct __solid
-
{
-
char s[100];
-
};
-
-
extern struct __solid solid;
-
The statement on line 1 declares the type struct __solid. The statement on line 6 declares (not does not define) the variable solid. The declaration tells the compiler that the symbol exists somewhere and that it should not create it.
Then in one of your C files include
This actually defines the symbol(variable) solid, but specifically limits the definition to a single C fgile so the symbol is only defined once across all files. The the declaration in the header lets all C files access the symbol.
A few notes on best practice
- It is considered bad form to have global data that just anyone can access. It causes maintenance issues and is a major contributor to bugs. If you need persistent data declared at the top of a file then provide access to it via functions rather than just let anyone access it.
- _ at the start of a symbol name, as you have done with __solid is reserved for platform internal types, variables and functions and should be avoided. It is a common convention to add an _t to the end of type names as in solid_t or in our company we have the convention of type names starting with a capital letter Solid.