How to enable a specific c++ warning in Visual Studio - c++

my project warnlevel is /w3.
I want to enable as single warning from warnlevel 4.
Such as "C4296 'operator' : expression is always false"
How can I do this in cxx flags of my CMake file?

Just add to your main CMakeLists.txt (CMake version >= 2.8.12) generally
add_compile_options("$<$<CXX_COMPILER_ID:MSVC>:/w34296>")
or (thanks #tambre for the hint) just to a specific target
target_add_compile_options(MyTarget "$<$<CXX_COMPILER_ID:MSVC>:/w34296>")
The shwon generator expression will add warning C4296 to warning level 3 for MSVC compilers (for the VC warning options see link provided by #Richard Critten)
Some more possibilities for setting compile option with CMake in Visual Studio projects can be found in my answer given here.

This code works for me.
#enable compiler warning C4296 in warnlevel 3
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /w34296 ")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /w34296 ")

Related

How can cmake_minimum_required required version impact generated files?

I'm experiencing a strange behaviour where changing cmake_minimum_required affects files generated by CMake targetting Visual Studio 2019. According to the doc of cmake_minimum_required:
If the running version of CMake is lower than the required version it will stop processing the project and report an error
So it's just supposed to interrupt project generation.
But, if I create:
main.cpp:
int main()
{
#ifndef _DEBUG
#error "DEBUG flag not set"
#endif
return 0;
}
and CMakeLists.txt:
cmake_minimum_required(VERSION 2.8.12)
project(hello_world)
set( CMAKE_CONFIGURATION_TYPES "Debug;Release;MyDebug" CACHE INTERNAL "" FORCE )
set( CMAKE_CXX_FLAGS_MYDEBUG "${CMAKE_CXX_FLAGS_DEBUG}" )
set( CMAKE_C_FLAGS_MYDEBUG "${CMAKE_C_FLAGS_DEBUG}" )
set( CMAKE_EXE_LINKER_FLAGS_MYDEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG}" )
set( CMAKE_SHARED_LINKER_FLAGS_MYDEBUG "${CMAKE_SHARED_LINKER_FLAGS_DEBUG}" )
set_property( GLOBAL PROPERTY DEBUG_CONFIGURATIONS "Debug;MyDebug" )
add_executable(app main.cpp)
If I generate this project with CMake 3.24.1 for Visual Studio 2019, then it builds correctly using MyDebug config as _DEBUG compilation flag is correctly set.
However, if I change cmake_minimum_required(VERSION 2.8.12) to cmake_minimum_required(VERSION 3.24.1), then it fails to build, reporting DEBUG flag not set, meaning _DEBUG compilation flag is not set anymore.
When I check vcproj file, I see that for MyDebug, <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> is changed to <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>.
Is this a CMake bug or am I doing something wrong?
So it's just supposed to interrupt project generation.
That's not the case at all!
cmake_minimum_required puts your project into a backwards compatibility mode consistent with the version specified. The "Policy Settings" section of that doc talks about this. There are a set of now over one hundred CMake policies that enable breaking improvements to the system. You can see the full list here: https://cmake.org/cmake/help/latest/manual/cmake-policies.7.html
The relevant policy here is CMP0091 which was introduced in CMake 3.15.
CMake 3.15 and above prefer to leave the MSVC runtime library selection flags out of the default CMAKE_<LANG>_FLAGS_<CONFIG> values and instead offer a first-class abstraction. The CMAKE_MSVC_RUNTIME_LIBRARY variable and MSVC_RUNTIME_LIBRARY target property may be set to select the MSVC runtime library. If they are not set then CMake uses the default value MultiThreaded$<$<CONFIG:Debug>:Debug>DLL which is equivalent to the original flags.
So to upgrade your project to a version of CMake newer than 3.15, you'll just need to override the default CMAKE_MSVC_RUNTIME_LIBRARY close to the top of your CMakeLists.txt file:
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug,MyDebug>:Debug>DLL"
CACHE STRING "Rule for selecting MSVC runtime")
This uses the $<CONFIG> generator expression to enable the debug runtime for your custom MyDebug config.
Of course cmake can change behaviour with its evolution.
As CMake evolves it is sometimes necessary to change existing behavior in order to fix bugs or improve implementations of existing features. *
If it just changes some behaviour in a new version, it introduces a policy, that can explicitly switch cmake to use an old behaviour. The OLD behavior of a policy becomes deprecated by definition and may be removed in a future version of CMake.
See what is changed in the list cmake-policies(7).
Also you can set cmake_minimum_required incrementing the major version number by one at a time, run cmake and see what policies were introduced in cmake dump. One of them is changing the behaviour of RuntimeLibrary and _DEBUG.

GCC compiler in CLION not found in PATH so cannot compile simple C++ program

When I try to compile a simple main.cpp consisting of:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
CLION tells me that:
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
CMake Error at CMakeLists.txt:2 (project):
The CMAKE_C_COMPILER:
C:/cygwin64/bin/gcc.exe
is not a full path and was not found in the PATH.
Tell CMake where to find the compiler by setting either the environment
variable "CC" or the CMake cache entry CMAKE_C_COMPILER to the full path to
the compiler, or to the compiler name if it is in the PATH.
I get the same block of messages for the CMAKE_CXX_COMPILER: referring to file C:/cygwin64/bin/g++.exe.
Both MAKE files exist in folder C:\cygwin64\bin and this path is referred to as an environment variable in Windows.
Looking at other questions posted concerning this kind of problem, I have checked the version settings of the compiler in CLION and I have:
And the MAKE settings are:
Can anyone please advise what I am missing here in order for the program to build and run?
In the CMakeLists.txt file I have also specified:
cmake_minimum_required(VERSION 3.16)
project(HelloWorld1)
set(CMAKE_C_COMPILER C:\cygwin64\bin)
set(CMAKE_CXX_COMPILER C:\cygwin64\bin)
add_executable(HelloWorld1 main.cpp)
But the result is still the same.
It's known regression in CLion 2020.1 which will be fixed in the upcoming update.
As Workaround I removed custom compiler path from Toolchains setting page in CLion. It detects the same compiler and it works.

Cannot set __cplusplus to C++17 standard with Visual Studio and CMake

I've a CMake project that's opened with Visual Studio 2019. I need c++17 features for my code, so I've set the corresponding flag in the CMakeLists.txt
cmake_minimum_required (VERSION 3.10.0)
project (datalog)
message (STATUS "Building project ${PROJECT_NAME}")
find_package(stxxl CONFIG REQUIRED)
include_directories (${CMAKE_SOURCE_DIR}/src)
set (PROJECT_SRC
main.cpp
)
add_executable (${PROJECT_NAME} ${PROJECT_SRC})
target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17)
target_link_libraries(${PROJECT_NAME} stxxl)
When I build I obtain a lot of errors, because the library that I'm linking, stxxl, installed with vcpkg, has the following piece of code:
STXXL_BEGIN_NAMESPACE
template <class Type>
struct compat_unique_ptr {
#if __cplusplus >= 201103L && ((__GNUC__ * 10000 + __GNUC_MINOR__ * 100) >= 40400)
typedef std::unique_ptr<Type> result;
#else
// auto_ptr is inherently broken and is deprecated by unique_ptr in c++0x
typedef std::auto_ptr<Type> result;
#endif
};
STXXL_END_NAMESPACE
The problem is that __cplusplus has value 199711L instead of the correct value 201703L, so code tries to use auto_ptr that's removed in C++17 standard.
I've also tried to set the flag manually in Visual Studio, adding this section in the CmakeLists.txt
if(MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std:c++17 /Zc:__cplusplus")
endif()
But nothing changes. I'm also using some C++17 features, so going back at the moment is not an option.
I can manually update the stxxl header file to get rid of the macro, but it's a workaround, and every developer should create the same fix. Instead, I'd like to know why I'm getting the error and how to set the macro to the correct value with Visual Studio and CMake. Do you have any suggestion?
As far as i can tell from this, you need to add /Zc:__cplusplus manually (at least for now).
Your CMakeList snippet worked for me, are you sure, that __cplusplus is actually set incorrectly and it's not just the __GNUC__ Macro, that's missing?
That said, I'd recommend to test if the version of VisualStudio is actually new enough:
# /Zc:__cplusplus is required to make __cplusplus accurate
# /Zc:__cplusplus is available starting with Visual Studio 2017 version 15.7
# (according to https://learn.microsoft.com/en-us/cpp/build/reference/zc-cplusplus)
# That version is equivalent to _MSC_VER==1914
# (according to https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=vs-2019)
# CMake's ${MSVC_VERSION} is equivalent to _MSC_VER
# (according to https://cmake.org/cmake/help/latest/variable/MSVC_VERSION.html#variable:MSVC_VERSION)
if ((MSVC) AND (MSVC_VERSION GREATER_EQUAL 1914))
target_compile_options(stxxl INTERFACE "/Zc:__cplusplus")
endif()
Note: I used target_compile_options to add the necessary option to the interface of your library target. This way all targets, that depend on that library (via target_link_libraries) will be compiled with that flag, but targets, that don't need it (and might be incompatible with it) won't get it.
If you want to add the flag to one of your own targets, you can use target_compile_options(stxxl PUBLIC "/Zc:__cplusplus") (PUBLIC instead of INTERFACE). INTERFACE means the option is used when other targets depend on that target, PRIVATE means the option is used for the target itself and PUBLIC means both. (IMHO this artical explains it well.)
Apart from that, you shouldn't set the c++ standard version via compile flags, but instead using target_compile_features if the newer version is required and using
set_target_properties(your_target_name PROPERTIES CXX_STANDARD 17) if you just wish to use the newer version if it is available.
In your case the latter is probably sufficient as your codesnippet has a fallback if the c++ version is older.
If changing the code of stxxl (via pull request, etc.) is an option, the code could test _MSVC_LANG and _MSC_VER. This way it would work without requiring /Zc:__cplusplus.
I think what you need is target_compile_definitions, where you can define arbitrary macros in CMake and pass to compiler.

Linker error when enabling Link Time Optimization in NDK

When I add the flag -flto to my NDK C++ project the linker emits the following error: "Optimization level must be between 0 and 3", even though my optimization level is explicitly set to 3 via -O3.
Does anyone know how to solve this?
The compiler flags are passed via Gradle which, as I understand it, should pass the flags to both the Clang compiler and linker. When I remove the -flto flag everything works fine.
Notes:
I'm using NDK 19.2 (latest version at the time I write this).
I also get the warning "clang++.exe: warning: argument unused during compilation: '-Wa,--noexecstack' [-Wunused-command-line-argument]" which I do not have if I compile without link time optimizations.
Two parts to the answer:
The error is caused by https://github.com/android-ndk/ndk/issues/721. Clang's LTO plugin just doesn't accept -Os or -Oz. This is a bug.
Okay, I might be really stupid, I suppose between 0 and 3 means 1 or 2 :)
It's actually because you can't use the generic cppFlags to set optimization levels. That corresponds to CMAKE_CXX_FLAGS, and you need to set these in CMAKE_CXX_FLAGS_DEBUG and CMAKE_CXX_FLAGS_RELEASE (and/or the C flavors of those). CMake has its own defaults in those variables and the command line is built as ${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE}, so your -O3 is being overridden by the default.
I also encounter this linking error but I fixed through a different way.
I had cross-compile a library for android with architectures of both arm64 and armv7. It's all OK for arm64 but encounter the linking error for armv7. And I found it can be fixed by commented out the following statements in my CMakeLists.txt:
if (${CMAKE_MAJOR_VERSION} GREATER_EQUAL 3 AND ${CMAKE_MINOR_VERSION} GREATER_EQUAL 9)
cmake_policy(SET CMP0069 NEW)
set(CMAKE_POLICY_DEFAULT_CMP0069 NEW)
include(CheckIPOSupported)
check_ipo_supported(RESULT ipo_supported OUTPUT ipo_supported_output)
if (ipo_supported)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
endif ()
endif ()
The above CMake statements are related to the IPO setting and it seems cause the linking error when cross-compiling for android armv7.
I don't know why the IPO should not enabled for android armv7.

#ifdef DEBUG with CMake independent from platform

I am using CMake for building my projects on Windows (Visual Studio) as well as on Linux machines(gcc). I'd like to mark some code as "debugging only", like with
#ifdef DEBUG
//some logging here
#endif
The question is: what compiler definition is available on all platforms in the CMake "Debug" build type? DEBUG seems not to exist. (I want to have the logging or whatever only when the build type is Debug.)
CMake adds -DNDEBUG to the CMAKE_C_FLAGS_{RELEASE, MINSIZEREL} by default. So, you can use #ifndef NDEBUG.
I would suggest that you add your own definition. The CMake symbol CMAKE_C_FLAGS_DEBUG can contain flags only used in debug mode. For example:
C:
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DMY_DEBUG")
C++:
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DMY_DEBUG")
In your code you can then write the following:
#ifdef MY_DEBUG
// ...
#endif
(Maybe, you would have to use "/DMY_DEBUG" for visual studio.)
In CMake >= 2.8, use target_compile_definitions:
target_compile_definitions(MyTarget PUBLIC "$<$<CONFIG:DEBUG>:DEBUG>")
When compiling in Debug mode, this will define the DEBUG symbol for use in your code. It will work even in IDEs like Visual Studio and Xcode for which cmake generates a single file for all compilation modes.
You have to do this for each target [1]. Alternatively you can use add_compile_options (Cmake >= 3.0):
add_compile_options("$<$<CONFIG:DEBUG>:-DDEBUG>")
Note that recent versions of Visual C++ (at least since VS2015) allow either / or - for parameters, so it should work fine across compilers. This command is also useful for other compile options you might like to add ("/O2" in release mode for MSVC or "-O3" for release mode in G++/Clang)
[1] : Note: in CMake >= 3.12 (currently beta) there is also an add_compile_definitions that supports generator expressions, which affects all targets.
I'm using the following in my CMakeLists.txt:
set(IS_DEBUG_BUILD CMAKE_BUILD_TYPE STREQUAL "Debug")
# Indication to the code that this is a debug build
if (${IS_DEBUG_BUILD})
add_compile_definitions(__DEBUG__)
endif ()
Then, in my code, I can write:
#ifdef __DEBUG__
// blablabla
#edif
My minimum CMake version:
cmake_minimum_required(VERSION 3.16.3)