Search code examples
if-statementgccassemblyarmgnu-assembler

GNU assembler- How to use .ifdef with logical AND,OR


In C I am able to use

#if defined(MULTI_CORE) || defined(CORE_INDEX)

How to achieve the same result in arm assembly file (using .ifdef or .if or any other supported expression)? I am using GCC compiler toolchain.


Solution

  • Use C preprocessor syntax in .S files exactly as you would in .c / .h. Build your code with gcc -c foo.S (not as directly), which causes gcc (the compiler front-end) to run your file through CPP before feeding it to as.

    Thus CPP stuff happens entirely before and separately from any .if GAS macro stuff.

    .ifdef and other GAS macro functionality isn't designed to replace CPP. You're supposed to use CPP (or m4 or whatever) as a preprocessor for your asm source.


    Note that using as directly on a .S will often build without error messages on x86, because # is the comment character in GAS syntax for that target. e.g. put #if 0 / #endif around some instructions: they will be in foo.o after as -o foo.o foo.S. All the #if lines are treated as comments.

    On ARM you should get noisy failure, because the comment character is @ (# is used in immediates). If you really wanted to guard against accidentally building without CPP on any platform, you could #define THIS_FILE_NEEDS_CPP then on the next line write THIS_FILE_NEEDS_CPP THIS_FILE_NEEDS_CPP. (Twice so it's not a valid label declaration). With CPP macro processing, this becomes a blank line instead of an invalid insn. as removes // and /* */ comments on its own, so you can't just use that. But most people don't do anything special; their build scripts work and they don't randomly build .S files without CPP.

    See also: