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
asm(
"mov r0, r0\n\t"
"mov r0, r0\n\t"
"mov r0, r0\n\t"
"mov r0, r0"
);
#else
// This is X86 assembly code
asm(
"movl %eax, %ebx\n\t"
"movl $56, %esi\n\t"
"movl %ecx, $label(%edx,%ebx,$4)\n\t"
"movb %ah, (%ebx)"
);
#endif
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:
Here are some similar posts that you may be interested in:
There's 0 Comment So Far
Share your thoughts, leave a comment!