Say I wanted to create a header file for my program. Would the variables in the header be defined globally for the file that it is attached to.
Code: ( text )
//header.h
//#ifndef HEADER_EXAMPLE
//#define HEADER_EXAMPLE
char array[10] ={"hello world"};
//prog.c
//#endif
#include <stdio.h>
#include "header.c" //#include <header.c>
{
printf("%s", &array);
return 0;
}
Let's takes this in pieces:
1) This header can be included in many source files. Each time it is included, its contents become part of the object file for that source file. When the linker combines the object files to create your executable, and variables created in the header file will be duplicated in each object file. Your build dies here with redefinition errors.
RULE 1: Header files contain declarations and not definitions.
A declaration says a thing exists. A definition is the code that creates it.
-
extern int data; //declaration. data is not in this file
-
-
int data; //definition. data is created right here
-
-
void MyFunction(int); //declaration. The function is not in this file
-
-
void MyFunction(int arg) //definition. This is the actual function.
-
{
-
cout << arg << endl;
-
}
-
The business with the #ifndef has to do with protecting against complications resulting from including the same header more than once in the same source file.
You get into this pickle when you include HeaderA and HeaderB and each of these includes HeaderC. When Header C is included the second time you die with redefinition errors again.
So, you need to be sure HeaderC is include only once. The common practice is to use an
inclusion guard. This is a series of preprocessor directives.
-
#ifndef XXX
-
#define XXX
-
-
// header file contents here
-
#endif
-
The first time the header is included XXX is not define. Hence the "if-not-defined" preprocessor directive evaluates to true and you define XXX and then include the header file contents. The #endif terminates the area affected by the #ifndef.
The second time the header is included (in the same source file, remember) the #ifndef evaluates to false because XXX was defined during the first inclusion. Hence, the preprocessor skips to the #endif neatly bypassing the header file contents.
RULE 2: All header files need inclusion guards.
RULE 3: The symbol defined (XXX) needs to be unique among all header files ever written or this scheme doesn't work. Making XXX a unique thing is left to your imagination.
RULE 4: Because of RULE 1, you never include source files.
-
#include <MyStuff.c> //Big no-no.
-
#include <MyStuff.cpp>
-