简体   繁体   中英

C++ Preprocessor include and define trouble with multiple files

I'm going to abstract my problem to avoid including unneeded details, but if needed I can provide the source code. I'm using visual studio.

I have the following files - all header files have #pragma once:

  • A.cpp //(containing my main function)
  • Bh
  • B.cpp //(Plays no role)
  • Ch
  • C.cpp

And here is how the preprocessor commands are set up:

A.cpp   #defines UseOptionOne
A.cpp   #includes B.h

B.h     #ifdef UseOptionOne   
            #defines Func as f1() //(calling a function that prints a msg)   
        #else                 
            #defines Func as [blank]  

A.cpp   #includes C.h
C.h     #includes B.h     // (B.h have #pragma once, so it doesnt get included again)

Here's how the function calls are set up:

A.cpp   main function uses Func          //- It prints as intended 
A.cpp   calls function in C.cpp // this function does the following:
        {
           #ifndef UseOptionOne
             exit(0)                    //- Doesn't happen, so UseOptionOne is defined
           #endif   
           uses Func                        //- DOES NOTHING?????
        }
A.cpp   uses Func                       //- It prints as intended 

I don't understand how this is possible? UseOptionOne is confirmed to still be defined in Ch but the Func is defined differently???

Can anyone explain this? or would you want me to provide you with my rather complicated solution or some code fragments maybe?

I'm really lost :(

EDIT: I have used breakpoints to confirm that the C.cpp function is called, the 'Func' is simply treated as blank

EDIT2: I can't answer my own question due to lack of reputation, so im putting it here:
I created a new project implementing my abstract description and it did trigger the exit in the #ifndef
So there is no way any of you could solve the problem with this description. I'm just going to have to look through everything again and find the mistake/error.

My two cents:

UseOptionsOne is defined only for A.cpp and for classes that includes Ah: in your case, it's defined only in A.cpp

C.cpp has no reference to Ah, so it does not see the define. In this case, UseOptionOne is not declared in C.cpp, it uses the blank function.

when you go out of the scope of C.cpp, and return in the scope of A.cpp, the function works because in that scope UseOptionOne is defined.

If you want to use the define in all files, you can create a separate definitions.h header and put in it the definitions, and then include that file in all headers for which you want the definition to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM