tags:

views:

82

answers:

3

Say I have a constant:

#define PI 3.14

Say I have a static library with multiple header and source files. If I declare this in the header file, will its scope apply to all of the source files? Or do the source files need to include the header with the declaration of PI?

+3  A: 

They will need to include the file which contains #define PI 3.14, otherwise the preprocessor will not read the #define line, and subsequently the compile will fail.

In C++, a good way to think of the compile process is that each individual C++ file is first run through a preprocessor, which takes all the #define, #include, and other preprocessor statements and replaces them throughout the code, then compiled (at this point, the C++ file and anything brought in via #include treated almost as if they were one very large single file), then after that, a linker takes the final output of the preprocess/compile stage for all of the C++ files and assembles them into one final output file. The preprocessor (Which handles the defines) works before the compile stage, not during linkage.

Sukasa
It's probably clearer to say that there are three stages: preprocessing, compiling, and linking, and that the `#define` and `#include` are preprocessor directives, so they take place before compilation.
Jefromi
Jef: Done, thanks
Sukasa
A: 

They will need to include the define, however if you need a define across all files you can do a compiler level switch.

Brian R. Bondy
+1  A: 

The definition has to be included in each module.

Technically, it has no "scope". It is only a text replacement operation that happens prior to compilation. You could also look into your compiler settings for a way to specify pre-processor definitions. This is often a project setting available easily through your IDE.

Erik Hermansen