Using CMake compile flags in preset for non-external projects only - cmake

I am adding a few external projects to my application. For instance, gtest.
In my CMake preset I set the following...
{
"version": 4,
"cmakeMinimumRequired": {
"major": 3,
"minor": 23,
"patch": 0
},
"configurePresets": [
{
"name": "debug",
"displayName": "debug",
"binaryDir": "${sourceDir}/build",
"cacheVariables": {
"CMAKE_CXX_FLAGS": "/W4 /Wall /EHsc",
"CMAKE_CXX_STANDARD": "20",
"CMAKE_CXX_STANDARD_REQUIRED": "YES",
"CMAKE_CXX_EXTENSIONS": "OFF"
}
}
]
}
When I build with the above preset, I get a bunch of warnings from building gtest. I only would like to see the warnings coming from my internal build, not external projects.
In my root CMakeLists.txt I have the following...
cmake_minimum_required(VERSION 3.23.0)
project(ProjectName LANGUAGES C CXX CUDA)
include(CTest)
add_subdirectory(external) # This has a bunch of external dependencies.
add_subdirectory(src) # This builds a normal executable.
add_subdirectory(tests) # This has various unit tests.
Is there a way for me to make sure the flags are only used for my personal project, and nothing external?
I have looked into "https://cmake.org/cmake/help/v3.23/manual/cmake-presets.7.html" but nothing stood out to me.
Thank you

If you want to localize your settings you should not use globals. Use target_compile_options and other target_* commands instead of setting CMAKE_CXX_* global (cache) variables in your preset.
Alternatively, you can choose not to build external projects as part of your local project build. With that organization you wouldn't have the problem in the first place.

Related

How to call a bash script from cmake and pass a generator dependent string as argument?

While using the Unix Makefiles generator I have added the following to a CMakeLists.txt file:
add_custom_target(maintainer-clean
# The current directory is CMAKE_CURRENT_BINARY_DIR.
COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/cwm4/scripts/cmake_maintainer_clean.sh $(MAKE) \"${GITACHE_PACKAGES}\"
)
This cmake_maintainer_clean.sh script is make specific, and it needs to use $(MAKE) in the generated Makefile when calling the script.
However, when switching to the generator Ninja this custom command is put as-is in the build.ninja file, causing the $ of the $(MAKE) to cause problems (ninja refuses to run any target, failing to parse build.ninja).
Therefore, I wish to make this generator-specific. How can I use $(MAKE) as first argument to the script when the generator is Unix Makefiles and something else, without a $ - e.g. "ninja" - when the generator is Ninja?
Can I do something like:
COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/cwm4/scripts/cmake_maintainer_clean.sh $<UNIX:$(MAKE),ninja> \"${GITACHE_PACKAGES}\"
?
I would make separate presets for each generator, so you can associate a particular environment variable with it. Here is how the CMakePresets.json file may look like:
{
"version": 2,
"cmakeMinimumRequired": {
"major": 3,
"minor": 20,
"patch": 0
},
"configurePresets": [
{
"name": "base",
"binaryDir": "${sourceDir}/build",
"hidden": true
},
{
"name": "Ninja",
"inherits": "base",
"displayName": "Ninja Config",
"generator": "Ninja",
"environment": {
"SCRIPT_ARG": "Ninja"
}
},
{
"name": "Make",
"inherits": "base",
"displayName": "Make Config",
"generator": "Unix Makefiles",
"environment": {
"SCRIPT_ARG": "Make"
}
}
]
}
Where the SCRIPT_ARG can be read later inside of the CMakeLists.txt configuration:
cmake_minimum_required(VERSION 3.20)
project(Hello)
add_executable(Hello main.cpp)
add_custom_target(my-script
COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/script.sh $ENV{SCRIPT_ARG}
)
add_dependencies(Hello my-script)
Providing script.sh is as simple as this:
#!/bin/sh
echo "Hello from script, $1!"
You will end up with the following output during build phase:
% cmake --preset Make
...
% cmake --build build
Hello from script, Make!
[ 0%] Built target my-script
...
Corresponding output for Ninja generator would be:
% cmake --preset Ninja
...
% cmake --build build
Hello from script, Ninja!
[ 0%] Built target my-script
...
If you need something more complex than an environment variable, you can introduce condition statement based on value of CMAKE_GENERATOR:
cmake_minimum_required(VERSION 3.20)
project(Hello)
add_executable(Hello main.cpp)
if(CMAKE_GENERATOR STREQUAL Ninja)
add_custom_target(my-script COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/script.sh $ENV{SCRIPT_ARG})
elseif(CMAKE_GENERATOR STREQUAL "Unix Makefiles")
add_custom_target(my-script COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/another_script.sh)
endif()
add_dependencies(Hello my-script)
The provided solutions work at build step, and for the part whether it's possible to distinguish between generators during build system generation phase (e.g. with use of generator expressions) i don't think it's possible, because the configuration is generator-agnostic at this point.

How to set working directory in CMake Visual Studio 2022?

I have a problem with setting the working directory with CMake (Visual Studio 2022).
I'm currently working on a project (some OpenGL learning stuff) and decided to switch from typical VS solution-project to CMake project. I need to load some files (.obj, shaders) from Resources folder (LearnOpenGL/Resources) but I see that paths in c++ code are relative to LearnOpenGL/out/build/x64-Debug/.
I've already tried :
setting property VS_DEBUGGER_WORKING_DIRECTORY like (also without trailing slash):
set_property(TARGET LearnOpenGL PROPERTY VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/")
adding "currentDir" or "cwd" to CMakeSettings.json like:
"currentDir": "${projectDir}"
"cwd": "${projectDir}"
but there is no effect of any of those changes. Does anyone have some ideas what else can I do? Or maybe I'm doing here something wrong?
You can add currentDir property to your launch.vs.json which will typically be in ${workspaceRoot}/.vs directory.
To access it from Visual Studio 2022 CMake project you can follow these steps:
In the solution explorer click on Switch between solutions and available views button:
Then click on CMake Targets View
Now right click on your project and press Add Debug Configuration in context menu
This will open launch.vs.json file where you can edit currentDir property, for example - my project 02_texture.exe should start in root directory so my launch config looks like this:
{
"version": "0.2.1",
"defaults": {},
"configurations": [
{
"type": "default",
"project": "CMakeLists.txt",
"projectTarget": "",
"name": "CMakeLists.txt"
},
{
"type": "default",
"project": "CMakeLists.txt",
"projectTarget": "02_texture.exe (02_texture\\02_texture.exe)",
"name": "02_texture.exe (02_texture\\02_texture.exe)",
"currentDir": "${workspaceRoot}"
}
]
}

Can I use the environment to add/replace to the CMAKE_MODULE_PATH?

Within a CMakeLists.txt file, you can write something like:
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules")
but what if I want to "prime" that variable before the invocation of CMake? Using the environment, perhaps? Is this possible?
The documentation says it is empty by default, but I was hoping to diverge from this default.
CMAKE_MODULE_PATH is not an "cmake-env-variable". It won't read same name environment variable to initialize it automatically. As an example, CMAKE_EXPORT_COMPILE_COMMANDS can be initialized from env var (ref).
An alternative for your situation:
if(DEFINED ENV{CMAKE_MODULE_PATH})
set(CMAKE_MODULE_PATH "$ENV{CMAKE_MODULE_PATH}")
else()
message(WARNING "CMAKE_MODULE_PATH env var not defined, using the default empty one")
endif()
My preferred option would be to pass this to cmake at the time of configuration.
Using command line options
cmake -D "CMAKE_MODULE_PATH:STRING=${CMAKE_MODULE_PATH}" -S ...
or
Using a cache configuration script
# initialCache.cmake
set(CMAKE_MODULE_PATH $ENV{CMAKE_MODULE_PATH} CACHE STRING "path to look for cmake modules")
cmake -C initialCache.cmake -S ...
or
Using a preset
CMakePresets.json
{
"version": 3,
"cmakeMinimumRequired": {
"major": 3,
"minor": 19,
"patch": 0
},
"configurePresets": [
{
"name": "mypreset",
"displayName": "My preset",
"description": "Preset using the environment variable to set CMAKE_MODULE_PATH",
"cacheVariables": {
"CMAKE_MODULE_PATH": {
"type": "STRING",
"value": "$env{CMAKE_MODULE_PATH}"
}
}
}
]
}
cmake --preset mypreset -S ...

Setting up platform-specific default tasks in VS Code

Broader Question:
This post originally asked about how to specify a platform-specific problem matcher, but it seems that the more important question to be answered is:
How do you set up platform-specific properties for tasks when those properties are not recognized in the "windows" or "linux" sections?
Even if I break this task into two tasks, it seems that only one of them can be set as the default build task for both platforms.
Before anyone asks, this problem stems from the need to commit my tasks.json file to the repository so that the other developers are able to build the project on any platform using the "Run Build Task..." command in VS Code. I realize they could always change the default task after checking out the code.
Original Question:
I have a task in VSCode that runs a shell/batch script for building my C++ (CMake) application. The task makes use of the "windows" and "linux" keys for platform-specific commands.
{
"label": "Build x64",
"type": "shell",
"windows": { "command": "${workspaceRoot}/Build-Win-x64.bat" },
"linux": { "command": "${workspaceRoot}/Build-Linux-x64.sh" },
"group": { "kind": "build", "isDefault": true }
}
The Windows script builds with the MSVC compiler which requires putting "problemMatcher": "$msCompile" in the task so that VSCode can parse the compiler output.
However the Linux script uses GCC which requires "problemMatcher": "$gcc".
These values seem to be mutually exclusive and VSCode does not allow them inside the platform-specific properties.
Is there any way to set up a default build task with different problem matchers for each platform?
I've thought about using an environment variable like this "problemMatcher": "${env:VSCODE_CPP_MATCHER}" but this would be annoying to set up for every workstation that works with this project.
It turns out that you can use an array of problem matchers!
{
"label": "Build",
"windows": { "command": "${workspaceFolder}/Build-Win-x64.bat" },
"linux": { "command": "${workspaceFolder}/Build-Linux-x64.sh" },
"problemMatcher": ["$msCompile", "$gcc"]
}
Since this solution lets me use the same task for Windows and Linux, I don't need to define separate default build tasks for each platform.
Just out of curiousity, is it possible to set up a different default build task for each platform?

How to disable link time code generation in CMake

We are using CMake with the Visual Studio 2015 generator and I am trying to disable link time code generation for libraries and executables under the debug build configuration. It seems that when I modify the linker flags with
SET_TARGET_PROPERTIES(${_PROJNAME} PROPERTIES LINK_FLAGS_DEBUG "${LINK_FLAGS_DEBUG} /LTCG:OFF")
that CMake still generates solutions with /LTCG:INCREMENTAL in the linker additional options but also with /LTGC:OFF appended. Does anyone know a way to turn LTCG off completely for all configurations so I can enable it just for those that we want it enabled for?
cmake version 3.10.0-rc2
If something ends up under "Additional Options" in the generated VS projects, it means CMake didn't recognize the option given (and therefore didn't replace its own default).
See CMake's source cmVS141LinkFlagTable.h:
{ "LinkTimeCodeGeneration", "", "Default", "Default", 0 },
{ "LinkTimeCodeGeneration", "LTCG:incremental", "Use Fast Link Time Code Generation", "UseFastLinkTimeCodeGeneration", 0 },
{ "LinkTimeCodeGeneration", "LTCG", "Use Link Time Code Generation", "UseLinkTimeCodeGeneration", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGInstrument", "Profile Guided Optimization - Instrument", "PGInstrument", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGOptimize", "Profile Guided Optimization - Optimization", "PGOptimization", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGUpdate", "Profile Guided Optimization - Update", "PGUpdate", 0 },
But if I look at CMake's VS 2015 defaults:
CMAKE_EXE_LINKER_FLAGS = /machine:X86
CMAKE_EXE_LINKER_FLAGS_DEBUG = /debug /INCREMENTAL
CMAKE_EXE_LINKER_FLAGS_RELEASE = /INCREMENTAL:NO
There is no /LTCG:INCREMENTAL in the defaults. So I think what you are actually looking for/what would help you is:
set_property(
TARGET ${_PROJNAME}
APPEND_STRING
PROPERTY
LINK_FLAGS_DEBUG " /INCREMENTAL:NO"
)
You could manually modify CMake cache variables CMAKE_EXE_LINKER_FLAGS_DEBUG, CMAKE_MODULE_LINKER_FLAGS_DEBUG, CMAKE_SHARED_LINKER_FLAGS_DEBUG and CMAKE_STATIC_LINKER_FLAGS_DEBUG as wished.
You could remove the /INCREMENTAL flag from these variables.