Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scope of #undef C++


I have a question about using #undef to redefine macros.
I have a file global.h which contains a number of #define-d macros. In the code that uses these macros, I find that the values that the macros hold are not generic enough. I want to redefine the macros to make them more generic. I wrote the following code snippet to do just that:

 std::cout << endl << "Enter pitch threshold:" << endl;  
 std::cin >> pitchT;  
 #ifdef PitchThreshold  
  #undef PitchThreshold  
  #define PitchThreshold pitchT   
  #endif  

My questions are:
Does using a #undef in this manner ensure redefinition of the macro across all source files, or is it local to the function where the above lines of code are written? What is the scope of the #undef and #define operators?
What can I do (apart from changing the macros in the file where they are #define-d itself) to ensure that the macro definitions are changed across all source files?
Thanks,
Sriram

like image 936
Sriram Avatar asked Dec 16 '22 20:12

Sriram


2 Answers

#ifdef is a preprocessor directive, this means that it will be applied before your source code is compiled. It means that only the source code 'below' will be affected. If you run your source code through the preprocessor you'll be able to see the result. That will give you more insight in the workings of the preprocessor.

like image 51
Sebastiaan M Avatar answered Dec 24 '22 02:12

Sebastiaan M


The scope of the #undef operator is the whole file after it's called. This includes all files that include it (because the preprocessor just chains the files together.) Because it's part of the preprocessor it doesn't have weird things like scope.

like image 38
OmnipotentEntity Avatar answered Dec 24 '22 03:12

OmnipotentEntity