Mohit Deshpande
Mohit Deshpande

Reputation: 55247

#Define's scope throughout library?

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?

Upvotes: 1

Views: 1534

Answers (3)

Sukasa
Sukasa

Reputation: 1700

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.

Upvotes: 4

Erik Hermansen
Erik Hermansen

Reputation: 2379

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.

Upvotes: 1

Brian R. Bondy
Brian R. Bondy

Reputation: 347556

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

Upvotes: 0

Related Questions