CMake: how to set COMPILE_FLAGS for header files? - compilation

I've successfully used CMake to built a shared library, but the size is not so good.
I've already tried several compile flags to cut size, etc.
set_source_files_properties(${TARGET_SOURCE_FILES} PROPERTIES COMPILE_FLAGS "-fexceptions")
Code above is used to open exception handling for single file while -fno-exceptions is added to CMAKE_CXX_FLAG. It works fine.
However, I used the same code to an *.hpp to open rtti for it while -fno-rtti is added to CMAKE_CXX_FLAGS. Unfortunately, it didn't work.
So, is there a way to add COMPILE_FLAGS to header files in CMAKE? I've viewd documentary on offical site, but still no clues.

This is not possible and probably a questionable thing to do in the first place.
Mixing different compile flags within the same binary is a dangerous game. Usually you would want all compilation units in a target to share the same compile flags, as it is very easy to mess things up subtly but terribly otherwise. However, CMake still allows you to use source file properties the way you did to do this if you are really sure what you are doing.
With header files though, things are worse. Headers do not get compiled on their own, so what you are asking for is that all source files that pull in that header will inherit the special compilation options associated with that header. But since all calls to the compiler happen based on source files, this would require to re-run CMake on every source change, check all the includes in all the source files, and adapt the compiler options accordingly. Hopefully you can now see why CMake doesn't want to do this.
What you can do though is specify those options on a per-target basis. Move your headers to an interface target and add a corresponding interface property there. Then, all targets that want to use the header will have to pull in that target as a dependency. As a consequence, all depending source files will get the special compile flags, regardless of whether they actually do include the header or not, but that's just how build systems work:
add_library(my_headers INTERFACE)
target_include_directories(my_headers INTERFACE ${PATH_TO_HEADERS})
target_compile_options(my_headers INTERFACE $<$<CXX_COMPILER_ID:GNU>:-fexceptions>)
add_executable(client a.cpp)
target_link_libraries(client PUBLIC my_headers)
In this example, a.cpp (as well as all other sources of client) will now get compiled with the -fexceptions flag.

Related

How can I add command-line options file to CMake compiler flags?

GCC allows for having command-line options passed by a file by #file syntax. Using this the file should be added as prerequisite (aka dependency) to the target.
I'm not finding any reference in CMake docs about argument files, suggesting it's not supported. Or perhaps just takes a little bit more plumbing, e.g. cat file|xargs? Or some way telling CMake explicitly that the file is a prerequisite? I mean "Prerequisite" according to GNU Make terminology. If file contents change I have to rebuild. AKA dependency.
Which is it? And how does it work?
You should just be able to use target_compile_options() or CXX_<LANG>_FLAGS like you normally would.
Since the flags available for different compilers are usually different, you probably will have one for each compiler you support, in which case you can wrap your target_compile_options() calls with if() blocks based on CMAKE_CXX_COMPILER_ID or the MSVC variable, or use the CXX_COMPILER_ID or X_COMPILER_ID generator expressions to use the right file (if you have multiple files for multiple compilers) for the right compiler.
However, I've also noticed before when trying this that using file flags like this doesn't automatically add the file as a dependency to the target (the CMake won't add a rule for the target to rebuild if that file changes), so you might need to do that manually like this:
# wrap this in a function taking `target` as an argument.
get_target_property(sources ${target} SOURCES)
set_property(SOURCE ${sources}
# DIRECTORY "${PROJECT_SOURCE_DIR}" "${PROJECT_BINARY_DIR}"
TARGET_DIRECTORY ${target}
APPEND PROPERTY OBJECT_DEPENDS "${PROJECT_SOURCE_DIR}/path/to/flags/file.txt"
)
The above snippet courtesy of a user in this GitHub issue. It uses the OBJECT_DEPENDS source file property to make every source file of a target depend on the compiler options file. I (and the author of that code snippet) would classify it as a workaround, since it only works for Generators that support OBJECT_DEPENDS. From the CMake docs:
Specifies a semicolon-separated list of full-paths to files on which any object files compiled from this source file depend. On Makefile Generators and the Ninja generator an object file will be recompiled if any of the named files is newer than it. Visual Studio Generators and the Xcode generator cannot implement such compilation dependencies.
I'm not sure at what level of the toolchain it would be best to request that such automatic dependency-tracking functionality be added. According some of the Ninja buildsystem maintainers in the above linked GitHub issue, (if my noob brain is understanding the words they're saying correctly :P), it's something that could be handled by compilers when they generate depfiles given a compile comand for a source file. I'm currently too scared to ask compiler maintainers if that's the case. If you're interested in digging onto the part that CMake plays in orchestrating other tools to get dependency tracking for things like header files and the creation of dependency-tracking files ("depfiles"), you can go to your CMake installation's Modules folder and grep for CMAKE_DEPFILE_FLAGS_. Then use "find in files" at https://github.dev/Kitware/CMake.
Notes: Visual Studio / MSVC's compiler calls these "command files", gcc doesn't seem to have a particular name for them, and clang calls these "configuration files". They all support similar #file syntax. I'm not sure what the history is with that, but many compilers aim to have levels of compatibility (similar interface to) with GCC.
That's all. If you're bored and want to read a bit about how CMake does header dependency detection (which is loosely related here on the topic of depfiles), see this other post of mine.

Ccache doesn't work with gcc -M flag?

I'm trying to use ccache to speed up my rebuilds and I noticed this in the log:
[2015-04-17T10:41:45.845545 27682] Compiler option -M is unsupported
[2015-04-17T10:41:45.845584 27682] Failed; falling back to running the real compiler
In my experience you need something like the -M flag in order to have make or its equivalent trigger rebuilds correctly. It seems weird that ccache would be tripped up by an option that must be in almost every project's build. Am I missing something? Is there a more preferred option?
This is w/ ccache-3.2.1.
Edit: I tried with -MM as well, no luck.
It is correct that ccache currently doesn't support the compiler options -M and -MM (and it never has supported them).
Some reasons for why the options in question are unupported:
The options tell the compiler to let the preprocessor output make rules instead of the preprocessed source code. This is not a good match for how ccache works; it needs to get hold of the "real" preprocessed output for each compiler invocation (see https://ccache.dev/manual/3.7.11.html#_how_ccache_works).
Nobody has implemented support for the mentioned options, simply put.
It would most likely be possible to implement support by letting ccache run the compiler command twice: one without -M/-MM to retrieve the preprocessed source code (with which the result should be associated) and one with -M/-MM to retrieve the result (make rules).
However, I (speaking as the ccache maintainer for the last six years) have not heard anybody missing support for -M/-MM until now, so my impression is that -M/-MM actually aren't used much.
Am I missing something? Is there a more preferred option?
Yes, I would say that the standard way is to use -MD/-MMD (which are supported by ccache) instead of -M/-MM. -MD/-MMD are superior because they produce both the .o and the .d file in one go, whereas -M/-MM only produce the .d file, so the compiler must in that case be invoked twice by the Makefile for each source code file. See for instance http://www.microhowto.info/howto/automatically_generate_makefile_dependencies.html for how to use -MD/-MMD.

How do I tell ld to ignore a missing library?

I'd like to define a Makefile with implicit rules for a bunch of executables, some of which require linking against a custom-built library (let's call it libedich.a).
My problem is that I'd like to be able to build those executables that do not require libedich.a when the latter hasn't been built yet. If I simply add -ledich to the LDLIBS variable, I get errors when libedich.a doesn't exist:
/usr/bin/ld: cannot find -ledich
How do I tell ld that it's okay to continue linking when a given library doesn't exist?
A common solution is to create a dummy archive so that GCC will find it. Since the executable doesn't need any symbols from the library, it won't error out. Like this,
# create an empty archive.
ar cru libedich.a
or even simpler,
echo '!<arch>' >libedich.a
This is the downside of using one LDLIBS variable to hold all of the library dependencies and re-using it for every target, even though you know some targets only need a subset of the libraries. You have several options:
There are probably fancy IDE's and build tools out there that try to infer library dependencies from context, saving you from manually specifying them for each target.
Switch to using shared libraries.
Fix the target in your Makefile so that it depends on libedich.a (even if it doesn't need to). This will work if you are building everything anyway and don't care what order the targets proceed in.
Manually specify the library dependencies for each target in your Makefile.
The last option is my recommendation; it is more work, but eliminating the false dependencies in your Makefile will enable you to build (perhaps most of) your targets even if one of the dependencies is broken. One convenient way to do this is with target-specific variables:
targetname::LDLIBS+=-ledich
You probably also want to be aware of make --keep-going (make -k)

The g++'s -g option equivalent to VS2010 cl compiler?

With g++ with -g option, I can use gdb for debugging purposes.
What's the equivalent to this option with Visual Studio 2010 cl.exe compiler?
This page has different libraries (debug/release) for linking.
If I compile with debugging option with cl.exe, do I have to use the corresponding library linking options (/MD/MT vs /MDd/MTd)?
There are a few separate pieces to this question: how to tell the compiler/linker to generate and preserve "debug information" (mapping between source code and object code), how to tell the compiler to compile the code differently to make debugging easier (think of assert() and #ifdef _DEBUG), and whether the precompiled libraries you link into your project include debugging information.
-Zi (flag to the CL compiler to tell it to generate debug information) is the equivalent of gcc's -g flag.
(There are other forms of the -Z option: -ZI if you want the "edit and continue" support in the Visual Studio IDE, but if you're using the IDE you're probably using its interface to the compiler settings instead of manipulating them directly, and -Z7 if you want the old CodeView-format debug information; whenever I've invoked CL directly it's always been -Zi that I wanted.)
Note that using the -Zi (or -ZI) option will generate a .pdb file per directory, usually, but when you link code together, it may have come from .obj files represented in different .pdb files, and you also want to combine those separate .pdb files into a master one representing the code you linked together -- this is what the -debug switch for the linker is for.
Also note: this may sound counterintuitive, but always use -Zi (for CL) and -debug (for link.exe). Even for code you're going to release. It doesn't increase the size of your executable, or give away secrets to your customers, since the debug information goes in a separate .pdb file (which you won't ship to customers). If there's any chance you're ever going to have to debug it, you're going to want the .pdb. (-Zi isn't even incompatible with optimizations, though -ZI is. So you might want to compile your "debug" builds with -ZI, and your "release" builds with "-Zi -O2".)
As for the libraries: you don't strictly need to match the debug/release property of the C runtime library with whether your code includes debugging information, but it's usually a good idea -- if you're going to debug the project you want to be able to debug all of it, and if you're not going to debug it you don't need the extra weight. Using debug/release versions of a given library won't affect whether it has debug symbols available (hopefully, if whoever compiled the library understood the point I made in the previous paragraph), but it will affect things like assert and extra #ifdef _DEBUG code in that library.
This goes for all libraries you link with, but especially for the C runtime library -- Microsoft added extra error-detection code to malloc() and free(). So if anything in your project is using the debug flavor of the CRT library, all of it should be.
The /M options (/MTd and /MDd) are weird and magic, in my opinion -- they're just aliases for a complicated set of other stuff going on behind the scenes. Take /MDd for example, documented to "Defines _DEBUG, _MT, and _DLL and causes your application to use the debug multithread- and DLL-specific version of the run-time library. It also causes the compiler to place the library name MSVCRTD.lib into the .obj file." Here, it's affecting both the preprocessor (defining _DEBUG and some other preprocessor symbols) and the linker (it actually puts a #pragma comment(linker) in your source code). If you care about what's going on and don't understand it, this can cause real problems -- I've seen a lot of projects that don't use the IDE get bogged down in warnings about both msvcrt.lib and msvcrtd.lib being linked in, etc. By the time you understand how to use these (/M options) safely, you don't really need them any more! I prefer to make things explicit: specify "-D _DEBUG" directly where I need it, specify which libraries to link with explicitly (and use -nodefaultlib), and then the /M options aren't needed.
You're looking for one of the debug information generation options (/Z7, /Zi or /ZI).
If you use one of those, you should also pass the /DEBUG option to the linker.
You will also need to link against the debug version of the runtime libraries (/MDd or /MTd). This is important because these versions are different from their release counterparts (e.g. their memory allocations routines are not compatible).

Problem with linking in gcc

I am compiling a program in which a header file is defined in multiple places. Contents of each of the header file is different, though the variable names are the same internal members within the structures are different .
Now at the linking time it is picking up from a library file which belongs to a different header not the one which is used during compilation. Due to this I get an error at link time.
Since there are so many libraries with the same name I don't know which library is being picked up. I have lot of oems and other customized libraries which are part of this build.
I checked out the options in gcc which talks about selecting different library files to be included. But no where I am able to see an option which talks about which libraries are being picked up the linker.
If the linker is able to find more than one library file name, then which does the linker pick up is something which I am not able to understand. I don't want to specify any path, rather I want to understand how the linker is resolving the multiple libraries that it is able to locate. I tried putting -v option, but that doesn't list out the path from which the gcc picks up the library.
I am using gcc on linux.
Any help in this regard is highly appreciated.
Regards,
Chitra
Passing -Wl,-t to gcc will tell ld to dump which files it's reading.

Resources