Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable from CMAKE in C++

Tags:

c++

cmake

I want to use a value declared in my CMakeLists.txt in my C++ code. I've tried to do like that :

ADD_DEFINITIONS( -D_MYVAR=1 )

and

#if -D_MYVAR == 1
    #define var "someone"
#else
    #define var "nobody"
#endif
int main(){
    std::cout << "hello" << var << std::endl;
    return 0;
}

But it doesn't work, and I don't understand why. Maybe I don't use ADD_DEFINITIONS correctly...

Ideally, I wish do something like that :

ADD_DEFINITIONS( -D_MYVAR=\"someone\" )

and

#define var D_MYVAR

int main(){
    std::cout << "hello" << var << std::endl;
    return 0;
}

Is it possible ?

Thanks !

like image 438
cooow Avatar asked Jul 09 '26 04:07

cooow


2 Answers

add_definitions ( -DVARNAME=... )

is the correct way of using add_definitions.

To check for a constant then, use

#ifdef VARNAME
...
#endif

Thanks to πάντα ῥεῖ

His solution works for my first question, and I've could do that :

CMakeLists.txt:

ADD_DEFINITIONS( -D_VAR=\"myValue\" )

main.cpp:

#include <iostream>

#ifdef _VAR
    #define TXT _VAR
#else
    #define TXT "nobody"
#endif

int main(){
    std::cout << "hello " << TXT << " !" << std::endl;
    return 0;
}
like image 41
cooow Avatar answered Jul 10 '26 17:07

cooow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!