LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Guess the kernel and platform the code is compiling on (https://www.linuxquestions.org/questions/programming-9/guess-the-kernel-and-platform-the-code-is-compiling-on-316755/)

Nerox 04-24-2005 04:30 PM

Guess the kernel and platform the code is compiling on
 
Hi there. I'm wondering if my source code (by means of gcc, of course) can guess the kind of kernel my machine is using and the platform it's being currently running on.
Something that looks like this:
Code:

#ifdef X86
      ... /* Do something specific of x86 platform */
#elif IA64
      ... /* Do something specific of IA64 platform */
#endif
#ifdef LINUX
      ... /* Do something specific of Linux kernel */
#elif BSD
      ... /* Do something specific of BSD kernel */
#endif

It's like a predefined preprocessor constant by gcc.
Any ideas?

Thanks in advance.

rjlee 04-25-2005 04:39 PM

You can use GCC-specific predefined macros. This will work on all platforms, but only under gcc. To get a list, run
Code:

touch /tmp/foo.h gcc -dH /tmp/foo.h
Incedentally, it's usually considered bad practice to use #ifdef unnecessarily like you have done. It would be more readable to write your example as:
Code:

if(X86) {
      ... /* Do something specific of x86 platform */
} else if (IA64) {
      ... /* Do something specific of IA64 platform */
}

if(LINUX) {
      ... /* Do something specific of Linux kernel */
} else if(BSD) {
      ... /* Do something specific of BSD kernel */
}

This generates the same code, but also has the advantage that the compiler will point out errors in code that isn't used.


As an alternative, you could use a makefile, and define some constants:

Code:

CCFLAGS=-DKERN=`uname -s` -DKERN_VER=`uname -v` -DKERN_REL=`uname -r`-DHARDWARE=`uname -m` -DPROC=`uname -p`-DPLATFORM=`uname -p` -DOS=`uname -o`

target : gcc $CCFLAGS src1.c src2.c src3.c

This will work on most (all?) POSIX systems, regardless of the compiler.

Nerox 04-27-2005 03:49 PM

Thanks a lot rjlee. Do you know something more about the first method (gcc method)? A link or anything is appreciated. Thanks ever so much.

rjlee 04-27-2005 03:55 PM

A quick search on google yields up a list with descriptions at http://gcc.gnu.org/onlinedocs/gcc-4....defined-Macros


All times are GMT -5. The time now is 12:19 PM.