Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using define in a c header file

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?

like image 837
Pjryan Avatar asked Jan 31 '17 02:01

Pjryan


1 Answers

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.

like image 74
M.M Avatar answered Oct 19 '22 23:10

M.M