GCC’s Preprocessor Option ‘-D’ and Example Usage with #ifdef

What I’ve Learned Today:

Say that you have a program that you’d like to be able to compile for both ARM and x86 architectures, but you have portions of the code written in assembly language.  Obviously, assembly code written for an ARM CPU won’t compile and run on an x86 CPU, so how would you cleanly solve this problem without writing two different programs?  One suggestion would be to use #ifndef (see this page for an explanation) and the ‘-D’ flag when invoking the gcc compiler to tell the compiler to ignore a particular block of code.  Here is an example snippet of code that you might want to use in a program:

#ifndef X86
   // This is ARM assembly code which is preferred architecture
      "mov     r0, r0nt"
      "mov     r0, r0nt"
      "mov     r0, r0nt"
      "mov     r0, r0"
   // This is X86 assembly code
      "movl %eax, %ebxnt"
      "movl $56, %esint"
      "movl %ecx, $label(%edx,%ebx,$4)nt"
      "movb %ah, (%ebx)"

This program will be developed mostly for the ARM architecture, but we would like to be able to easily compile it for x86 as well. When we do want to compile for x86, we will use the command:

gcc -D X86 myprogram.c -o myprogram_x86

The -D flag is a preprocessor option which, in my understanding, sets a sort of #define for the program before compiling (see ‘man gcc‘ page). The preprocessor will check for any of the #ifndef or #ifdef lines of the program and then act accordingly. In this example, the lines between “#ifndef X86” and “#else” containing the ARM assembly code will be discarded and the lines between “#else” and “#endif” containing the x86 assembly code will be used.

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:

There's 2 Comments So Far

  • Jeevan
    July 23rd, 2014 at 1:16 pm

    thx a lot dude!!!!!

  • lim kok hole
    July 20th, 2015 at 4:41 am

    thanks, you saved my day 🙂

Share your thoughts, leave a comment!