13NP
13NP

Reputation: 27

Is it possible to define global variables in a function and use the variable in other function using preprocessor directives in C++?

I am trying to understand the preprocessor directives (like #if , #ifdef, #ifndef) and following is the code I have tried out.

Main_class.cpp Wrap.h file Output

Note: The member functions are further wrapped and used in python and hence the results show the python like calls but this does not affect any of the c++ process.

Question: 1. As per my understanding the global variables have a scope of whole file from the point it is declared. Then in this case, why is the defined value not accepted inside another function?

Requirement: I want to do something like mentioned below:

void Somefunc(int val){
 set variable x;
}

Based on the x value, I want to include functions. Now the condition is: If x=1, only some functions should be compiled since others utilize headers which would throw errors with the compiler I am using.

Thanks in advance!

Upvotes: 0

Views: 496

Answers (1)

krisz
krisz

Reputation: 2695

Preprocessing runs before compilation. It handles the source code as plain text, it doesn't care for C++ language semantics.

The reason why var is not defined is that a preprocessor definition is valid from the point of definition until the end of the file (preprocessed translation unit) or a corresponding #undef.

Upvotes: 1

Related Questions