Izzo
Izzo

Reputation: 4928

What is the scope of a #define?

What is the scope of a #define?

I have a question regarding the scope of a #define for C/C++ and am trying to bet understand the preprocessor.

Let's say I have a project containing multiple source and header files. Let's say I have a header file that has the following:

// header_file.h

#ifndef __HEADER_FILE
#define __HEADER_FILE

#define CONSTANT_1          1
#define CONSTANT_2          2

#endif

Let's then say I have two source files that are compiled in the following order:

// source1.c

#include header_file.h

void funct1(void)
{
    int var = CONSTANT_1;
}


// source2.c    

#include header_file.h

void funct2(void)
{
    int var = CONSTANT_2;
}

Assuming I have included all the other necessary overhead, this code should compile fine. However, I'm curious as to what #defines are remembered between compilations. When I compile the above code, are the contents of each #include actually included, or are the include guards actually implemented?

TLDR: Do #defines carry over from one compilation unit to the next? Or do #define only exist within a single compilation unit?

As I type this out, I believe I'm answering my own question and I will state my believed answer. #defines are constrained to a single compilation unit (.c). The preprocessor essentially forgets any #defines when it goes from one compilation unit to the next. Thus in the above example I listed, the include guards do not come into play. Am I correct in this belief?

Upvotes: 2

Views: 4896

Answers (3)

Kusalananda
Kusalananda

Reputation: 15633

Preprocessor macros do not have "scope" as such, they just define a piece of text that should replace the macro in the code.

This means that the compiler never sees the strings CONSTANT_1 and CONSTANT_2 but instead gets the source in a preprocessed form with these macros replaced with their expansions (1 and 2 respectively).

You may inspect this preprocessed source by calling gcc with the -E flag, or with whatever flag only does preprocessing on your particular compiler.

Upvotes: 1

Amit Kumar
Amit Kumar

Reputation: 59

Yes, you are right!! Compilation of a file, in it self, is merely, just a process under execution. One process can not interfare with another unless explicitly done. The c pre-processors are just literal substitution mechanism, performed in a dumb way. Whatever conditional checking are performed, are confined to ongoing instance of pre-processor only, nothing gets carry forward once execution (compilation) comes to end. Pre-processors do not "configure" compiler, their scope is limited till "their own compilation"

Upvotes: 0

crlanglois
crlanglois

Reputation: 3609

source1.c is compiled separately from source2.c therefore your defines are processed for source1 as it is compiled and then as an independent action they are processed for source2 as it is compiled.

Hopefully this is a clear explanation.

Upvotes: 4

Related Questions