Suppress compiler warnings from external library in CMake - c++

I am trying to build the following project https://github.com/whoshuu/cpr#cmake into my project by following their instructions for CMake reproduced below:
include(FetchContent)
FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/whoshuu/cpr.git GIT_TAG c8d33915dbd88ad6c92b258869b03aba06587ff9) # the commit hash for 1.5.0
FetchContent_MakeAvailable(cpr)
My project already had some other libraries linked with the main target so I included this new library as follows:
target_link_libraries(my_target PRIVATE cpr::cpr PUBLIC other_libraries)
The problem with this is that the warnings from building the cpr library are preventing the project from building. I would like to suppress these warnings. I have tried adding the SYSTEM keyword as recommended here: How to suppress GCC warnings from library headers? so the code would look as follows:
target_link_libraries(my_target PRIVATE SYSTEM cpr::cpr PUBLIC other_libraries)
but this did not help. Are there other methods to suppress warnings from external libraries in CMake? If it helps, I am using C++-17 g++-11 and Ninja.

The only way around I could find was to disable warnings using compiler pragmas within the code:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weverything"
#include <cpr/cpr.h>
#pragma GCC diagnostic pop
This is compiler dependent. If you use clang, simply replace "GCC" by "clang". On Visual Studio, use pragma warning... This can be made portable with macros, have a look at this article.

Related

CMake won't select the correct C++ compiler [duplicate]

I would like to use the IAR compiler. I noticed CMake has already have a bunch of files about this compiler:
https://github.com/jevinskie/cmake/blob/master/Modules/Compiler/IAR.cmake
From what I read the common solution is to specify manually ALL the toolchain in my CMakeLists.txt:
set(CMAKE_C_COMPILER iccarm)
set(CMAKE_CPP_COMPILER iccarm)
How CMake can link these definitions with `Modules/Compiler/IAR.cmake"?
I thought I would just have to do
include("Modules/Compiler/IAR.cmake")
What is the correct way to specify my IAR compiler?
When I do
cmake .
It still tries to use gcc instead of my IAR compiler. Why?
To select a specific compiler, you have several solutions, as exaplained in CMake wiki:
Method 1: use environment variables
For C and C++, set the CC and CXX environment variables. This method is not guaranteed to work for all generators. (Specifically, if you are trying to set Xcode's GCC_VERSION, this method confuses Xcode.)
For example:
CC=gcc-4.2 CXX=/usr/bin/g++-4.2 cmake -G "Your Generator" path/to/your/source
Method 2: use cmake -D
Set the appropriate CMAKE_FOO_COMPILER variable(s) to a valid compiler name or full path on the command-line using cmake -D.
For example:
cmake -G "Your Generator" -D CMAKE_C_COMPILER=gcc-4.2 -D CMAKE_CXX_COMPILER=g++-4.2 path/to/your/source
Method 3 (avoid): use set()
Set the appropriate CMAKE_FOO_COMPILER variable(s) to a valid compiler name or full path in a list file using set(). This must be done before any language is set (ie: before any project() or enable_language() command).
For example:
set(CMAKE_C_COMPILER "gcc-4.2")
set(CMAKE_CXX_COMPILER "/usr/bin/g++-4.2")
project("YourProjectName")
The wiki doesn't provide reason why 3rd method should be avoided...
I see more and more people who set CMAKE_C_COMPILER and other compiler-related variables in the CMakeLists.txt after the project call and wonder why this approach breaks sometimes.
What happens actually
When CMake executes the project() call, it looks for a default compiler executable and determines the way for use it: default compiler flags, default linker flags, compile features, etc.
And CMake stores path to that default compiler executable in the CMAKE_C_COMPILER variable.
When one sets CMAKE_C_COMPILER variable after the project() call, this only changes the compiler executable: default flags, features all remains set for the default compiler.
AS RESULT: When the project is built, a build system calls the project-specified compiler executable but with parameters suitable for the default compiler.
As one could guess, this approach would work only when one replaces a default compiler with a highly compatible one. E.g. replacement of gcc with clang could work sometimes.
This approach will never work for replacement of cl compiler (used in Visual Studio) with gcc one. Nor this will work when replacing a native compiler with a cross-compiler.
What to do
Never set a compiler in CMakeLists.txt.
If you want, e.g., to use clang instead of defaulted gcc, then either:
Pass -DCMAKE_C_COMPILER=<compiler> to cmake when configure the project. That way CMake will use this compiler instead of default one and on the project() call it will adjust all flags for the specified compiler.
Set CC environment variable (CXX for C++ compiler). CMake checks this variable when selects a default compiler.
(Only in rare cases) Set CMAKE_C_COMPILER variable before the project() call. This approach is similar to the first one, but makes the project less flexible.
If the ways above do not work
If on setting CMAKE_C_COMPILER in the command line CMake errors that a compiler cannot "compile a simple project", then something wrong in your environment.. or you specify a compiler incompatible for chosen generator or platform.
Examples:
Visual Studio generators work with cl compiler but cannot work with gcc.
A MinGW compiler usually requires MinGW Makefiles generator.
Incompatible generator cannot be fixed in CMakeLists.txt. One need to pass the proper -G option to the cmake executable (or select the proper generator in CMake GUI).
Cross-compiling
Cross-compiling usually requires setting CMAKE_SYSTEM_NAME variable, and this setting should normally be done in the toolchain file. That toolchain file is also responsible for set a compiler.
Setting CMAKE_SYSTEM_NAME in the CMakeLists.txt is almost always an error.
You need to create a toolchain file, and use the CmakeForceCompiler module.
Here is an example toolchain file for bare-metal ARM development with IAR:
include(CMakeForceCompiler)
set(CMAKE_SYSTEM_NAME Generic) # Or name of your OS if you have one
set(CMAKE_SYSTEM_PROCESSOR arm) # Or whatever
set(CMAKE_CROSSCOMPILING 1)
set(CMAKE_C_COMPILER iccarm) # Change the arm suffix if appropriate
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) # Required to make the previous line work for a target that requires a custom linker file
The last line is necessary because CMake will try to compile a test program with the compiler to make sure it works and to get some version information from preprocessor defines. Without this line, CMake will use add_executable() for the test program, and you will get the error "The C compiler "XXX" is not able to compile a simple test program." This is because the test program fails to link, as it doesn't have your custom linker file (I'm assuming bare-metal development since this is what IAR is usually used for). This line tells CMake to use add_library() instead, which makes the test succeed without the linker file. Source of this workaround: this CMake mailing list post.
Then, assuming that your toolchain file is named iar-toolchain.cmake, invoke CMake like this:
cmake -DCMAKE_TOOLCHAIN_FILE=iar-toolchain.cmake .
You can call cmake like this:
cmake -DCMAKE_C_COMPILER=iccarm ...
or
cmake -DCMAKE_CXX_COMPILER=...
If you don't want to use your PC's standard compiler, you have to give CMake the path to the compiler. You do this via environment variables, a toolchain file or direct definitions in the CMake command line (see e.g. CMake Error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found).
Putting the compiler's name/path into your CMakeLists.txt would stop your project from being cross-platform.
CMake does check for the compiler ids by compiling special C/C++ files. So no need to manually include from Module/Compiler or Module/Platform.
This will be automatically done by CMake based on its compiler and platform checks.
References
CMake: In which Order are Files parsed (Cache, Toolchain, …)?
CMake GitLab Commit: Add support files for C, C++ and ASM for the IAR toolchain.
IAR Systems recently published a basic CMake tutorial with examples under their GitHub profile.
I like the the idea of a generic toolchain file which works seamlessly for both Windows and Linux compilers using find_program().
The following snippet will be used for when using C and can be used similarly for CXX:
# IAR C Compiler
find_program(CMAKE_C_COMPILER
NAMES icc${CMAKE_SYSTEM_PROCESSOR}
PATHS ${TOOLKIT}
"$ENV{ProgramFiles}/IAR Systems/*"
"$ENV{ProgramFiles\(x86\)}/IAR Systems/*"
/opt/iarsystems/bx${CMAKE_SYSTEM_PROCESSOR}
PATH_SUFFIXES bin ${CMAKE_SYSTEM_PROCESSOR}/bin
REQUIRED )
For ASM, I initially got puzzled with the NAMES but then I realized that the toolchain file was made that way for working with old Assemblers shipped with XLINK:
find_program(CMAKE_ASM_COMPILER
NAMES iasm${CMAKE_SYSTEM_PROCESSOR} a${CMAKE_SYSTEM_PROCESSOR}
PATHS ${TOOLKIT}
"$ENV{PROGRAMFILES}/IAR Systems/*"
"$ENV{ProgramFiles\(x86\)}/IAR Systems/*"
/opt/iarsystems/bx${CMAKE_SYSTEM_PROCESSOR}
PATH_SUFFIXES bin ${CMAKE_SYSTEM_PROCESSOR}/bin
REQUIRED )
Also, take a look at the full toolchain file. It will work automatically for "Arm" when the tools are installed on their default locations, otherwise it is just about updating the TOOLKIT variable and the compilers for all the supported languages should adjust automatically.
If your wanting to specify a compiler in cmake then just do ...
cmake_minimum_required(VERSION 3.22)
set(CMAKE_C_COMPILER "clang")
set(CMAKE_CXX_COMPILER "clang++")
Options 1 is only used if you want to specify what compiler you want to use as default for everything that you might compile on your computer. And I don't even think it would work on windows.
Option 2 would be used if you only want to use a different temporarily.
Option 3 is used if that's the compiler that should be used for that particular project. Also option 3 would be the most cross compatible.

CMake: add conditional compiler flags into Visual Studio project

Visual Studio allows to select either the cl compiler or the clang-cl compiler to build projects -- these are called toolsets. These two compilers have different sets of flags, and in particular different flags for disabling warnings. Flags for one compiler produces errors on the other.
This problem can be solved in Visual Studio for both compilers at the same time by defining compiler flags conditionally based on the used toolset. Official documentation for that here.
I use CMake to generate the Visual Studio projects. How can I make CMake add such conditional flags for the generated Visual Studio projects?
You can use CMAKE_CXX_COMPILER_ID and CMAKE_CXX_SIMULATE_ID with your favourite way of handling compilers (if-else or generator expressions)
Output for -T ClangCL (Visual Studio 2019):
message(STATUS ${CMAKE_CXX_COMPILER_ID}) // Clang
message(STATUS ${CMAKE_CXX_SIMULATE_ID}) // MSVC
Output with no toolkit (Visual Studio 2019):
message(STATUS ${CMAKE_CXX_COMPILER_ID}) // MSVC
message(STATUS ${CMAKE_CXX_SIMULATE_ID}) // <empty>
Essentially a more modern approach to the earlier question here, you can use an if-statement to check the compiler type, and set compile flags based on that:
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
# Disable a Clang warning type.
target_compile_options(MyLib PRIVATE -Wno-unused-variable)
elseif(MSVC)
# Disable a MSVC warning type.
target_compile_options(MyLib PRIVATE /wd4101)
endif()
For putting this into a single expression, you can use CMake generator expressions (which are evaluated at the CMake buildsystem generation stage):
target_compile_options(MyLib PRIVATE
"$<IF:$<STREQUAL:${CMAKE_CXX_COMPILER_ID},Clang>,-Wno-unused-variable,/wd4101>"
)
For reference, here is a list of all of the clang warnings types.

Including directories for CLion inspections while using custom toolchain

I'm using CLion 2018.2 to write C/C++ code for a custom compiler toolchain which are not supported natively by CLion. I currently compile with make on the Terminal instead of building from within the IDE.
I have a custom include directory with header files which are not resolved/found by CLion since they are not part of the project. However, I want to get code inspection features for them. The headers are e.g. located at C:\devkitPro\wups\include.
I decided to use the include_directories() CMake command to improve CLion's ability to resolved code:
include_directories("C:\\devkitPro\\wups\\include")
Then I also modified the CMake include path:
set(CMAKE_INCLUDE_PATH "C:\\devkitPro\\wups\\include")
And also decided to link against the lib directory:
link_directories("C:\\devkitPro\\wups\\lib")
After doing all that, the headers still aren't resolved in CLion (but it still compiles using make of course). How can the header resolution be done with CLion or is it not possible, yet?
Depending on the configured toolchain in CLion, CMake expects a Windows or a WSL-style path. Inspections will work with the include_directories directive, e.g.
# Add extra include directories
if (WIN32) # When using a Windows compilation toolchain
set(WUT "/c/devkitPro/wut/include")
set(WUPS "/c/devkitPro/wups/include")
else () # When using WSL as toolchain
set(WUT "/mnt/c/devkitPro/wut/include")
set(WUPS "/mnt/c/devkitPro/wups/include")
endif ()
include_directories(${WUT})
include_directories(${WUPS})
A more detailed written tutorial can be found in this pull request.

Building POCO libraries with CMake in Windows

I am currently building POCO libraries with CMake like this:
cmake -DCMAKE_BUILD_TYPE=Debug -G "NMake Makefiles" -DPOCO_STATIC .
nmake
It all works fine, except for the fact that libraries aren't created with suffix mtd.lib or mdd.lib, just d.lib. Because of this, then my application fails to link to PocoFoundationsmdd.lib since the file doesn't exist.
Is there any keyword to pass in the cmake command so that it builds with the right prefix? I know that from Visual Studio there are configurations like debug_static_md one can select, but is it possible to do it through cmake without modifying the CMakelists.txt?
It was as simple as adding add_definitions( -DPOCO_STATIC -DPOCO_NO_AUTOMATIC_LIBS) to the CMakelists.txt that is consuming the POCO libraries compiled with cmake. That effectively disables the header (*.h) definitions that attempt to link from the code:
#if defined(_MSC_VER)
#if !defined(POCO_NO_AUTOMATIC_LIBS) && !defined(Crypto_EXPORTS)
#pragma comment(lib, "PocoXXX" POCO_LIB_SUFFIX)
#endif
#endif

Linking libc++ to CMake project on Linux

I want to use libc++ together with clang on Arch Linux in CMake project. I installed libc++ and added following lines to CMakeLists.txt as said on LLVM site in Linux section of "Using libc++ in your programs":
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++")
set(CMAKE_EXE_LINKER_FLAGS "-lc++abi")
I have tried just "++abi" in linker's flags, but it didn't help. I need some help in figuring out what i should write in my CMakeLists.txt.
Don't forget to set the compiler to clang++:
set(CMAKE_CXX_COMPILER "clang++")
Also, purge the cmake generated files (delete the folder CMakeFiles and CMakeCache.txt).
Depending on your system, it might also help to set
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -stdlib=libc++ -lc++abi")
The "proper" way to do this in CMake at the moment, until a specific base feature is added to switch standard libraries that is, is to use a toolchain file.
In that toolchain file you specify the compiler etc similarly to the other answers here.
BUT what's great about toolchains is they can be swapped out quickly either on the commandline (using -DCMAKE_TOOLCHAIN_FILE=path/to/file) OR in VSCode with CMakeTools extension installed, and probably other editors too.
But having to hand code your own toolchain files is yet another obscure chore! No fun!
Luckily, I stumbled upon this github that maintains a suite of them so you don't have to write them from scratch! Should be a lot less likely to get them wrong.
https://github.com/ruslo/polly