I am just starting to learn C so hopefully this isn't a dumb question. The problem I am having is regarding header files and using #define for constants. I have read that I should use the following to prevent my header from being compiled more than once.
#ifndef NAME_OF_FILE
#define NAME_OF_FILE
.
. //my header file content
.
#endif
I want to add a constant, and I believe I would also use a #define such as,
#ifndef NAME_OF_FILE
#define NAME_OF_FILE
#define NUM_CONST 5 //the constant I want in my header file
.
.
.
#endif
How does C know that #define NAME_OF_FILE is referring to the .h file while #define NUM_CONST 5 is just a constant? Is it because of the value at the end of NUM_CONST? Or do I have this all completely wrong?
There is no essential difference between the two defines. #define NAME_OF_FILE
and #define NUM_CONST 5
are the same sort of thing. They define a plaintext replacement of tokens (in the first case, the replacement is nothing).
For example you could put subsequent code:
printf("%d\n", NAME_OF_FILE NUM_CONST NAME_OF_FILE);
and after the above substitutions the code would turn in to:
printf("%d\n", 5);
which is correct. There is no "magic". The compilation step that performs these substitutions is usually known as "preprocessing".
NAME_OF_FILE
does not refer to the .h
file, per se, but the use of the ifndef
directive achieves the goal of not compiling the same code twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With