Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining C++ Preprocessor macros with SCons

Tags:

c++

macros

scons

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

like image 499
TSeabrook43 Avatar asked Oct 11 '13 00:10

TSeabrook43


People also ask

What does ## mean in C macro?

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.

Which preprocessor is used define macros?

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.

What is the difference between macro and preprocessor?

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.

Can you use a macro in a macro C?

Short answer yes. You can nest defines and macros like that - as many levels as you want as long as it isn't recursive.


1 Answers

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
like image 158
Brady Avatar answered Oct 16 '22 05:10

Brady