I'm trying to define a preprocessor macro within Scons for building a larger C/C++ project.
One of the libraries I'm using needs ALIGN defined. To be more specific, if I add
#define ALIGN(x) __attribute((aligned(x)))
to the header file of said library, it compiles fine. However, I should be able to specify this at build time, as this is how the library intends on being used. I know in CMake, I would be able to define the macro using something like
SET(ALIGN_DECL "__attribute__((aligned(x)))")
Defining constants in Scons like this
myEnv.Append(CPPDEFINES = ['IAMADEFINEDCONSTANT'])
works fine, but definine a macro in this way doesn't work. What gives?
Edit: fixed typo
The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.
Macro: a word defined by the #define preprocessor directive that evaluates to some other expression. Preprocessor directive: a special #-keyword, recognized by the preprocessor. Show activity on this post. preprocessor modifies the source file before handing it over the compiler.
Short answer yes. You can nest defines and macros like that - as many levels as you want as long as it isn't recursive.
I was able to do it on Linux with g++ as follows:
SConscript
env = Environment()
env.Append(CPPDEFINES=['MAX(x,y)=(x>y ? x:y)'])
env.Program(target = 'main', source = 'main.cc')
main.cc
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
int a = 3;
int b = 5;
// MAX() will be defined at compile time
cout << "Max is " << MAX(a, b) << endl;
}
Compilation
$ scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
g++ -o main.o -c "-DMAX(x,y)=(x>y ? x:y)" main.cc
g++ -o main main.o
scons: done building targets.
Execution
./main
Max is 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With