简体   繁体   中英

#if statements in c++ code

I'm using a 3rd party library, and I'm not compiling their sources, only including the headers from /usr/include .

I know that the source code contains a block like the following:

#if VAL1 && VAL2
    do something
#else
   do something I dont want to do
#endif

I know that VAL2 is set to 1 , but VAL1 is set to 0, in a different file included somewhere inside.

What I'm trying to do is define VAL1 myself, by copying the content of the header which sets VAL1 to 0 , and setting the value myself.

Is this going to make it so that when the code of the library runs, it will run into the first block? or is it totally static in the compilation time?

Preprocessor macros are compilation-time things. You usually use them to make sure compiler know how to behave in certain situation. For example when you're using different libraries for different platforms.

More info here

Is this going to make it so that when the code of the library runs, it will run into the first block? or is it totally static in the compilation time?

the answer is : it is totally static in the compilation time.

If you would like to compile both versions of your code then depending on context where this if/def macro is used you could:

if (VAL1 && VAL2)
{    do something }
else
{   do something I dont want to do }

then assuming VAL1 and VAL2 resolves to 1, the code do something will compile and execute, but the code do something I dont want to do will only compile - but compiler will optimize it out by not including it in resulting executable.

short answer: no

Those are preprocessor directives which are (as the name indicates) preprocessed before compilation. Once your program is compiled; you cannot change that behavior anymore.

No, this will only affect the header as it is parsed during your next compilation run. It'll have no effect on the compiled part of the library that you're already linking against.

This means it's probably a bad idea. In general you want to keep compiler flags consistent, and that includes macros. We cannot tell whether it'll make a difference here but, unless you're sure, I would stick with the same macro definitions.

If that means you have to recompile the library itself then that's what you'll have to do.

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