Preprocessing

T

tatto0_2000

Hi,

I am a bit confuse. If I have the header file hdr.h with the
following:

#ifndef HDR_H
#define HDR_H
#define a 10
#define b 20
#endif

In file1.c:
#include "hdr.h"
/* and other codes to access constant a and b after this */

In file2.c:
#include "hdr.h"
/* and other codes to access constant a and b after this */

If these 2 C files to be compiled in the same project, would it still
legal? Can I get access to both constants in both files?

Thanks.
 
E

Eric Sosman

Hi,

I am a bit confuse. If I have the header file hdr.h with the
following:

#ifndef HDR_H
#define HDR_H
#define a 10
#define b 20
#endif

In file1.c:
#include "hdr.h"
/* and other codes to access constant a and b after this */

In file2.c:
#include "hdr.h"
/* and other codes to access constant a and b after this */

If these 2 C files to be compiled in the same project, would it still
legal? Can I get access to both constants in both files?

Yes and yes. However, I think you do not understand
the nature of a and b. They are not "constants," but
"macros." After the #defines, each appearance of a or b
is recognized as a reference to a macro, and the reference
is replaced by the macro's definition. In this case, the
definitions are numeric constants, but other macros could
be defined differently. HDR_H, for example, is a macro
whose definition is empty: if you were to use HDR_H in the
code, the compiler would recognize it as a macro and replace
it with its definition, namely, nothing at all.

You need to re-read your C textbook until you understand
the difference between a macro and a variable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,139
Latest member
JamaalCald
Top