#Define's scope throughout library?

2019-08-04 01:35发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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