Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I identify x86 vs. x86_64 at compile time in gcc?

Tags:

c

linux

macros

I want to compile part of my code only on x86 and x86_64 linux, but not s390 linux or others. How to use the macro define in C to achieve it? I know linux is to determine linux OS, and 386, 486 and 586 to determine CPU architecture. Is there an easy macro define to determine x86 linux and x86_64 linux? Thanks

like image 976
JackChen255 Avatar asked May 09 '15 12:05

JackChen255


People also ask

How do I specify architecture in gcc?

If gcc -v shows GCC was configured with a --with-arch option (or --with-arch-32 and/or --with-arch-64 ) then that's what will be the default. Without a --with-arch option (and if there isn't a custom specs file in use) then the arch used will be the default for the target.

Is gcc 32 or 64-bit?

Compile 32-bit program on 64-bit gcc in C and C++Nowadays the compiler comes with default 64-bit version. Sometimes we need to compile and execute a code into some 32bit system. In that time, we have to use thisS feature. At first, we Shave to check the current target version of the gcc compiler.

What is EIP 64-bit?

Remember that EIP is the instruction pointer or program counter of 32 bit processes and RIP is the instruction pointer or program counter of 64 bit processes.


2 Answers

You can detect whether or not you are in a 64 bit mode easily:

#if defined(__x86_64__)
/* 64 bit detected */
#endif
#if defined(__i386__)
/* 32 bit x86 detected */
#endif
like image 122
David Hoelzer Avatar answered Oct 20 '22 00:10

David Hoelzer


If your compiler does not provide pre-defined macros and constants, you may define it yourself: gcc -D WHATEVER_YOU_WANT.

Additional reward: if you compile your code for, say, amd64, but you don't define amd64, you can compare the results (the version which use amd64-specific parts vs the generic version) and see, whether your amd64 optimalization worths the effort.

like image 42
ern0 Avatar answered Oct 20 '22 01:10

ern0