Use CXX to query preprocessor defines? - c++

I have a GNUmakefile that respects CXX and CXXFLAGS. It also performs some platform and architecture tests. Currently, the makefile assumes the host and target are the same:
IS_X86 = $(shell uname -m | $(EGREP) -c "i.86|x86|i86|amd64")
In an effort to improve robustness, I want to ask the tools what it is compiling for. I've come up with the following, but I'm not sure it is correct.
$ export CXX=clang++
$ export CXXFLAGS="-DNDEBUG -g2 -O3 -m32"
$ $CXX $CXXFLAGS -dM -E - < /dev/null | egrep "(i386|x86_64)"
#define __i386 1
#define __i386__ 1
#define i386 1
$ export CXX=clang++
$ export CXXFLAGS="-DNDEBUG -g2 -O3"
$ $CXX $CXXFLAGS -dM -E - < /dev/null | egrep "(i386|x86_64)"
#define __x86_64 1
#define __x86_64__ 1
My question is, will the above - with CXX and CXXFLAGS - work reliably to detect a target? Or do I need something else?
Here's the two reasons I ask. First, my experience with Autotools indicates something different. When Autotools performs a test like above, they test CPP, and sometimes CPP or CXX needs to include --isysroot (or other hacks) to get things configured properly.
Second, some toolchains, like Clang, integrate other components (like a preprocessor or assembler), so I can't use CPP directly under all circumstances.
In fact, doing something as simple as $CXX -Wa,-v - </dev/null (ask assembler for its version) results in an "unsupported option" error under Clang when using its integrated assembler. (Cf., With integrated assembler enabled, fail to fetch version string of assembler).
And just in case: this is not an Autools or Cmake project. It does not use Boost or any other libraries. Its a stand alone C++03 project.

My question is, will the above - with CXX and CXXFLAGS - work reliably to detect a target?
The answer is Yes, it will. The preprocessor or compielr driver (passing down to preprocessor) will mostly yield expected target defines with all else being equal. Notable exception is GCC and ARMv8/Aarch64, which is missing a slew of expected defines.
The thing to avoid is uname -m (and friends). Uname reports information on the host, and not the target.

Related

Automatically select a C++11-compatible g++ version in the Makefile

The problem:
2 version of g++ installed on a computer running Ubuntu 12.04. They are the versions 4.6 and 5.2.
I have to compile a C++11 program using a Makefile. If I use g++ as compiler it calls automatically the version 4.6, it does not support c++11 so the compilation fails. I've followed a tutorial online, so that now if I call g++ it calls automatically the version 5.2 and now it works.
I find this solution not so good, since it works only on my PC. Is there a way to recognize in the Makefile if the default g++ version support C++11 and, in case not, switch to a more recent version?
Thank you!
Is there a way to recognize in the Makefile if the default g++ version support C++11 and, in case not, switch to a more recent version?
You can certainly detect the version of the default compiler available in PATH in your makefile. However, where do you search for another version?
The standard approach is to let the user specify the C compiler through CC and C++ compiler through CXX make variables, e.g.: make CC=/path/to/my/gcc CXX=/path/to/my/g++.
You can always select which gcc to use while invoking make
make CXX=/gcc/path/of/your/choice
otherwise you can detect gcc version using
ifdef CXX
GCC_VERSION = $(shell $(CXX) -dumpversion)
else
GCC_VERSION = $(shell g++ -dumpversion)
endif
in Makefile and while using, you can test if your gcc is >=4.6
ifeq ($(shell expr $(GCC_VERSION) '>=' 4.6), 1)
UPDATE: newer gcc needs -dumpfullversion together (icx is the CC from Intel OneAPI)
$ icx -dumpversion
14.0.0
$ gcc -dumpversion
9
$ icx -dumpfullversion -dumpversion
14.0.0
$ gcc -dumpfullversion -dumpversion
9.3.1
One very simple way is to use conditional statements in your makefile, and go for versions which you know are compatible, and only use the default gcc as a fallback. Here's a basic example:
CXX=g++
ifeq (/usr/bin/g++-4.9,$(wildcard /usr/bin/g++-4.9*))
CXX=g++-4.9
# else if... (a list of known-to-be-ok versions)
endif
The other, more robust method, is to generate your makefile using a script that checks for capabilities using test compilations, kind of like what ./configure usually does. I really don't mean to recommend autotools, though.
The thing to do is build your Makefile to use as many implicit rules as possible. By default compilation uses various environment variables.
The variable $(CXX) is the C++ compiler command and defaults to g++ on Linux systems. So clanging CXX to a different compiler executable will change the compiler for all implicit compile commands.
When you write explicit rules use the same variable that the implicit rules use. So instead of this:
program: program.cpp
g++ -o program program.cpp
Do this:
program: program.cpp
$(CXX) -o program program.cpp
Other variables you should use are:
CPPFLAGS = -Iinclude
CXXFLAGS = -std=c++14 -g3 -O0
Those are for pre-processing flags CPPFLAGS and compiler flags CXXFLAGS and library linking flags LDLIBS.
Using the default environment variables allows the person compiling the project the freedom to control the compilation for their desired environment.
See the GNU make manual
This works for me:
cmake_minimum_required(VERSION 2.8.11)
project(test)
if (${CMAKE_CXX_COMPILER_VERSION} LESS 5.0)
message(FATAL_ERROR "You need a version of gcc > 5.0")
endif (${CMAKE_CXX_COMPILER_VERSION} LESS 5.0)
add_executable(test test.cpp)
You can check in your source code the gcc version and abort compilation if you don't like it. Here is how it works:
/* Test for GCC > 4.6 */
#if !(__GNUC__ > 3 && __GNUC_MINOR__ > 6)
#error gcc above version 4.6 required!
#endif

Get the compiler options from a compiled executable?

It there a way to see what compiler and flags were used to create an executable file in *nix? I have an old version of my code compiled and I would like to see whether it was compiled with or without optimization. Google was not too helpful, but I'm not sure I am using the correct keywords.
gcc has a -frecord-gcc-switches option for that:
-frecord-gcc-switches
This switch causes the command line that was used to invoke the compiler to
be recorded into the object file that is being created. This switch is only
implemented on some targets and the exact format of the recording is target
and binary file format dependent, but it usually takes the form of a section
containing ASCII text.
Afterwards, the ELF executables will contain .GCC.command.line section with that information.
$ gcc -O2 -frecord-gcc-switches a.c
$ readelf -p .GCC.command.line a.out
String dump of section '.GCC.command.line':
[ 0] a.c
[ 4] -mtune=generic
[ 13] -march=x86-64
[ 21] -O2
[ 25] -frecord-gcc-switches
Of course, it won't work for executables compiled without that option.
For the simple case of optimizations, you could try using a debugger if the file was compiled with debug info. If you step through it a little, you may notice that some variables were 'optimized out'. That suggests that optimization took place.
If you compile with the -frecord-gcc-switches flag, then the command line compiler options will be written in the binary in the note section. See also the docs.
Another option is -grecord-gcc-swtiches (note, not -f but -g). According to gcc docs it'll put flags into dwarf debug info. And looks like it's enabled by default since gcc 4.8.
I've found dwarfdump program to be useful to extract those cflags. Note, strings program does not see them. Looks like dwarf info is compressed.
As long as the executable was compiled by gcc with -g option, the following should do the trick:
readelf --debug-dump=info /path/to/executable | grep "DW_AT_producer"
For example:
% cat test.c
int main() {
return 42;
}
% gcc -g test.c -o test
% readelf --debug-dump=info ./test | grep "DW_AT_producer"
<c> DW_AT_producer : (indirect string, offset: 0x2a): GNU C17 10.2.0 -mtune=generic -march=x86-64 -g
Sadly, clang doesn't seem to record options in similar way, at least in version 10.
Of course, strings would turn this up too, but one has to have at least some idea of what to look for as inspecting all the strings in real-world binary with naked eyes is usually impractical. E.g. with the binary from above example:
% strings ./test | grep march
GNU C17 10.2.0 -mtune=generic -march=x86-64 -g -O3
This is something that would require compiler support. You don't mention what compiler you are using but since you tagged your question linux I will assume you are using gcc -- which does not default the feature you're asking about (but -frecord-gcc-switches is an option to perform this).
If you want to inspect your binary, the strings command will show you everything that appears to be a readable character string within the file.
If you still have the compiler (same version) you used, and it is only one flag you're unsure about, you can try compiling your code again, once with and once without the flag. Then you can compare the executables. Your old one should be identical, or very similar, to one of the new ones.
I highly doubt it is possible:
int main()
{
}
When compiled with:
gcc -O3 -ffast-math -g main.c -o main
None of the parameters can be found in the generated object:
strings main | grep -O3
(no output)

What are some of the most commonly used gcc/g++ flags for information (not just optimization)

I have found -E very useful to see preprocessor output and debug macros, and I have seen -fdump-class-hierarchy to look at the v-tables of a class hierarchy...I know there are flags to dump asm output as well..what are some other widely (or perhaps a bit unknown but very handy) flags akin to these?
Few flags which I like:
-x language: used to compile file with extension other than .c or .cpp
-s - dump asm.
-g - debug build.
gcc -O3 -Q --help=optimizers | grep disabled - will give you all optimization flags which remain diabled even after -O3
Wonderful place for all wonderful options

What does the gcc -R parameter do?

I am trying to run an autotools configure script for the bson-cpp project, and it fails because it cannot determine what flags it needs to compile with boost_filesystem. A quick look at confg.log shows:
g++ -o conftest -g -O2 -pthread -L/usr/local/lib -R/usr/local/lib -L/usr/local/libexec conftest.o -lboost_filesystem-mt -lboost_system-mt >&5
g++: error: unrecognized option '-R'
So, naturally, I tried to find out what the R option does, but I can't seem to find it documented anywhere. I've checked here and here to no avail. What does the option do and how do I tell autotools not to use it?
-R does not seem to be an option for g++ or gcc anywhere. -R may be a linker option on some platforms that is equivalent of -rpath to gnu ld, ... This seems to be a known bug in boost builds ... have a look at Use -Wl to pass arguments to the linker.
It actually has the patch available there
I am re-posting it for convenience, however PLEASE PLEASE look at the original URL linked above for official patch!
--- ../gnote/m4/boost.m4 2011-01-25 14:30:18.000000000 +0200
+++ m4/boost.m4 2011-02-27 20:57:11.686221539 +0200
## -403,7 +403,7 ##
LDFLAGS=$boost_save_LDFLAGS
LIBS=$boost_save_LIBS
if test x"$Boost_lib" = xyes; then
- Boost_lib_LDFLAGS="-L$boost_ldpath -R$boost_ldpath"
+ Boost_lib_LDFLAGS="-L$boost_ldpath -Wl,-R$boost_ldpath"
Boost_lib_LDPATH="$boost_ldpath"
break 6
else
It's an option similar to -rpath, but available only on some platforms. The script is maybe failing detecting your platform ?
It is not a valid option for GCC, so it does not do anything.
It is possibly a valid option for other compilers though, which could be why autoconf gives it a shot.
Not all errors in the config.log files are a problem. autoconf figures out a lot of things by "guessing", i.e. trying something and keeping that if it worked.

How to determine compilation flags at compile time on OS/X?

If I compile with -fPIC on x86 Linux with gcc 4.1, then the definition __PIC__ is set to 1 and the preprocessor can act on that at compile time. However, on OS/X under gcc 4.01 that is not the case. Is there some other way to determine the setting of -fPIC at compile time on OS/X?
A general facility for querying compilation flags at the preprocessor level under OS/X would be even more helpful, but I wasn't able to find anything like that.
-fPIC is the default on OS X. gcc 4.0.1 on my crufty old OS X 10.4 machine does define __PIC__; or, when it is explicitly turned off with -fno-PIC, it does not.
The settings of compilation flags are not in general exported to the preprocessor, except for certain special cases, which may vary across different GCC targets.
But you can see the effects of changing flags on the predefined preprocessor definitions, on any platform, using the -dM option to gcc, which dumps the preprocessor definitions after preprocessing is complete.
e.g. from a terminal window:
$ gcc -xc++ -dM -E /dev/null | sort > /tmp/defaults.txt
$ gcc -fno-PIC -xc++ -dM -E /dev/null | sort > /tmp/nopic.txt
$ diff /tmp/defaults.txt /tmp/nopic.txt
65d64
< #define __PIC__ 1
$
(I've specified -xc++ there because I'm preprocessing /dev/null rather than a file with an extension that indicates the language variant. That could also be -xc, -xobjective-c or -xobjective-c++.)