VĂsual Studio >=2010 does provide to configure system directories in the VC++ Directories section. Is there any way to tell CMake to fill these settings instead using C/C++/Additional Include Directories?
Since cmake 3.12 you can use variables like CMAKE_VS_SDK_INCLUDE_DIRECTORIES to setup "VC++ Include Directories".
Simply add the following line to your CMakeLists.txt:
include_directories(-your-include-folder-)
Similarly, add the following line if you want to set the library directories:
link_directories(-your-library-folder-)
As Min said, you can set CMAKE_VS_SDK_INCLUDE_DIRECTORIES now. Thank you Min!
I'll leave a working example for the next person that ends up here like I did.
cmake_minimum_required(VERSION 3.18)
# ...
if (MSVC)
# Example for a library that only exports as module without xxx_DIRS variables.
get_target_property(SDL2_image_INCLUDE_DIRS SDL2_image::SDL2_image INTERFACE_INCLUDE_DIRECTORIES)
# Join all include dependencies in a list
set(_DEPS_DIRS ${SDL2_INCLUDE_DIRS} ${SDL2_image_INCLUDE_DIRS} ${OpenCV_INCLUDE_DIRS})
# Make all slashes turn into backslashes
cmake_path(CONVERT "${_DEPS_DIRS}" TO_NATIVE_PATH_LIST _NATIVE_DIRS NORMALIZE)
# Set the "VC++ Directories > Include Directories" setting
set(CMAKE_VS_SDK_INCLUDE_DIRECTORIES "$(VC_IncludePath);$(WindowsSDK_IncludePath)" ${_NATIVE_DIRS})
unset(_DEPS_DIRS)
unset(_NATIVE_DIRS)
endif()
Important: To troubleshoot first delete the build folder and start from scratch.
I believe previously (before v3.18?) cmake added the list to the "Additional Include Directories" setting, but I think they removed it because those are added with /I compiler option, and now it seems included dependencies are added with /external:I if you look at Command Line settings in the project, and they may conflict? Not confirmed, just a thought.
Don't use target_include_directories or include_directories just for this. With modules you shouldn't need to, only use it if you already had to.
Also even if possible shouldn't include all headers as dependencies to add_executable, that's inconvenient.
Related
Suppose you're developing some library, myproj, using CMake for build configuration; supporting the cmake --install (using install() commands); and supporting use of myproj with CMake config mode, i.e. by making relevant .cmake files accessible to dependent projects.
Now, ,given an install root directory - where should I install my project's configuration .cmake files? Is there an idiomatic standard(ish) location?
Sorush Khajepor's R&D blog suggests ${LIB_INSTALL_DIR}/cmake/myproj - and it's the newest.
Foonathan's blog suggests placing the config .cmake files in ${LIB_INSTALL_DIR}/. So does Falkor's blog.
The documentation page for the CMakePackageConfigHelpers module suggests: ${LIB_INSTALL_DIR}/myproj/cmake.
What's the most popular/idiomatic choice? And what are its pros and cons relative to the other ones?
I advocate for setting a cache variable to override this and defaulting it to <LIBDIR>/cmake/ProjName (as you suggest in your answer):
cmake_minimum_required(VERSION 3.21) # for saner CACHE variables
project(ProjName VERSION 0.1.0)
# ...
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
set(ProjName_INSTALL_CMAKEDIR "${CMAKE_INSTALL_LIBDIR}/cmake/ProjName"
CACHE STRING "Path to ProjName CMake files")
install(EXPORT ProjName_Targets
DESTINATION "${ProjName_INSTALL_CMAKEDIR}"
NAMESPACE ProjName::
FILE ProjNameConfig.cmake
COMPONENT ProjName_Development)
write_basic_package_version_file(
ProjNameConfigVersion.cmake
COMPATIBILITY SameMajorVersion)
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/ProjNameConfigVersion.cmake"
DESTINATION "${ProjName_INSTALL_CMAKEDIR}"
COMPONENT ProjName_Development)
I wrote a blog post with an expanded version of this a while back: https://alexreinking.com/blog/building-a-dual-shared-and-static-library-with-cmake.html
In general, setting an install() destination to anything other than "${SOME_CACHE_VARIABLE}" is bound to cause headaches for some package maintainer. Where GNUInstallDirs doesn't provide a valid configuration point, you must create your own.
I'll argue in favor of ${LIB_INSTALL_DIR}/cmake/myproj.
If you're installing to some library-specific install location, e.g. /opt/myproj - then it doesn't really matter all that much anyway. But think about what happens when you install to, say, /usr/local.
If you place the scripts in ${LIB_INSTALL_DIR}, that library now becomes full of foo-config.cmake and foo-version-config.cmake, instead of just library files (and some subdirs). Less fun for browsing and searching.
If you place the scripts in ${LIB_INSTALL_DIR}/myproj/cmake, then - the same thing happens, but with per-project subdirs instead of sets of files. Better, perhaps, but instead - why don't we just replace the path elements of myproj and cmake, and that way we would get a cmake/ directory with many subdirs, instead. That's cleaner and more convenient IMHO.
I'm facing the following scenario:
Existing project which uses cmake
External 3rdparty library which only comes with Makefiles
The difference of my situation compared to existing questions is that I don't need to have cmake to build the 3rdparty library via the Makefile. Instead, the 3rdparty library provides a library.mk Makefile which has variables like LIB_SRCS and LIB_INCS containing all source and header files required to compile the library.
My idea is to include the library.mk into the project's CMakeLists.txt and then adding those $(LIB_SRCS) and $(LIB_INCS) to target_sources().
My question: How can I include library.mk into the existing CMakeLists.txt to get access to the $(LIB_SRCS) and $(LIB_INCS) for adding them to target_sources()? I'm looking for something like this:
include("/path/to/library.mk") # Somehow include the library's `library.mk` to expose variables to cmake.
add_executable(my_app)
target_sources(
my_app
PRIVATE
main.c
$(LIB_SRCS) # Add 3rd-party library source files
$(LIB_INCS) # Add 3rd-party library header files
)
Using include() does not work as the library.mk is not a CMake list/file.
Since you can't be sure that your target system will even have Make on it, the only option is to parse the strings out of the .mk file, which might be easy if the variables are set directly as a list of filenames, or really hard if they are set with expansions of other variables, conditionals, etc. Do this with FILE(STRINGS) cmake doc.
Your plan will only work if the Makefiles are trivial, and do not set important compiler flags, define preprocessor variables, modify the include directory, etc. And if they really are trivial, skip the parsing, and just do something like aux_source_directory(<dir> <variable>) to collect all the sources from the library directory.
You might also consider building and maintaining a CMakeLists.txt for this third-party library. Do the conversion once, and store it as a branch off of the "vendor" main branch in your version control system. Whenever you update, update the vendor branch from upstream, and merge or rebase your modifications. Or just store it in your existing project, referring to the source directory of the 3rd-party stuff.
I'm using the -imacros option for GCC in order to set all preprocessor defines (Options) for a project.
Before imacros I have been using a raw file with the preprocessor defines names and with a regular expression in CMAKE I was creating the list of -D to put in the CMAKE_C_FLAGS.
This works fine but ugly to see in the text editor. So to enhance that, I have changed to -imacros.
CMAKE_C_FLAGS will contain -imacros "path to configuration header"
This works fine, but if I change some configuration item in the configuration header the CMAKE do not recompile the file (don't see changes). In the old version - as you can expect - if some -D was changed all the files will be recompiled.
Any help?
An simple Approach
You can use OBJECT_DEPENDS source file property. But that needs to be set for all source files with something like:
set_source_files_properties(
${sources}
PROPERTIES
OBJECT_DEPENDS "path to configuration header"
)
Alternatives for all Source Files in Project
Officially CMake recommends to put all your definitions in a header file that is included by all your source files. The header could e.g. be generated from a template using configure_file().
But to follow your line of thought with using -imacros compiler flag, here are two alternative approaches for triggering a rebuild of all source files if "path to configuration header" file changes:
You can extend the scope of OBJECT_DEPENDS to all targets and their source files in the current directory with define_property(... INHERITED ...):
If the INHERITED option then the get_property() command will chain up to the next higher scope when the requested property is not set in the scope given to the command. DIRECTORY scope chains to GLOBAL. TARGET, SOURCE, and TEST chain to DIRECTORY.
So in your case this translates to:
define_property(
SOURCE
PROPERTY OBJECT_DEPENDS
INHERITED
BRIEF_DOCS "brief-doc"
FULL_DOCS "full-doc"
)
set_directory_properties(
PROPERTIES
OBJECT_DEPENDS "path to configuration header"
)
If I understand correctly, you anyway have to re-run CMake if your "configuration header" should/would change. Then you can simply add one definition outside your "configuration header" that keeps track of the header with something like:
file(TIMESTAMP "path to configuration header" _timestamp)
add_definitions(-DIMACROS_TIMESTAMP=${_timestamp})
Now every time your header gets a new timestamp, the definitions for all targets are changing and your build system will rebuild all source files.
I'm following a tutorial on CMake and I have problems understanding the necessity of using the 'include_directories' command at one point.
Let me explain the project first:
In my working directory I have:
- a main.cpp function, a CMakeLists.txt(the main one), a configuration file, a 'MathFunction' directory and a 'build' directory
In the MathFunction directory I have:
- a CMakeLists.txt file that will be invoked by the main one
- A file 'mysqrt.cxx' that contains the implementation of a function which will be used in 'main.cpp' application
- A 'MathFunctions.h' header file that contains the prototype of that function
In the CMakeLists from 'MathFunction' directory I'm creating a library using code from 'mysqrt.cxx' like this:
add_library(MathFunctions mysqrt.cxx)
This snippet is a part of my main CMake code:
# add the MathFunctions library?
#
if (USE_MYMATH)
include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions") # WHY DO WE NEED THIS
add_subdirectory (MathFunctions)
set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
add_executable(Tutorial tutorial.cxx)
target_link_libraries (Tutorial MathFunctions)
Now I do not understand why I need too add that 'include_directories' command in order to use the library? Shouldn't it be enough that the last command 'target_link_libraries' links the already created executable and libraries togheter so there would be no need to also include_directories?
Thank you for reading and I'm sorry if I have not explained it very well but I hope you will understand what I mean :D
Command include_directories sets directories for header files (.h) to be searched. Linking (target_link_libraries) with a library basically specifies only a library file (.so, .dll or other type). As you see, these are different things.
When linking executable with a library target, CMake propagates (more precisely, "consumes") some properties of that library target to the executable. Among these properties there is INTERFACE_INCLUDE_DIRECTORIES property, which adds include directories to the executable.
So, when a library target has INTERFACE_INCLUDE_DIRECTORIES property correctly being set, you don't need to explicitly specify include directories for executable:
MathFunctions/CMakeLists.txt:
add_library(MathFunctions mysqrt.cxx)
# Among other things, this call sets INTERFACE_INCLUDE_DIRECTORIES property.
target_include_directories(MathFunctions PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
CMakeLsits.txt:
add_executable(Tutorial tutorial.cxx)
# This also propagates include directories from the library to executable
target_link_libraries (Tutorial MathFunctions)
Note, that using simple
# This *doesn't* set INTERFACE_INCLUDE_DIRECTORIES property.
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
in MathFunctions/CMakeLists.txt doesn't imply propagating include directories to the linked executable.
I'm running into a problem with add_custom_command for a custom target (created using add_custom_target).
My general idea is to incorporate a static code analysis tool into the cmake tool-chain. My solution is based on the one described here: https://github.com/rpavlik/cmake-modules/blob/master/CppcheckTargets.cmake
In a nutshell, each project that I want to run static code analysis for has the following two lines of code:
include(cppcheck)
add_cppcheck(${le_project} STYLE POSSIBLE_ERROR FAIL_ON_WARNINGS)
The module has this at the top of the file:
if (NOT TARGET ANALYZE_CODE)
add_custom_target(ANALYZE_CODE WORKING_DIRECTORY ${LE_LITEN_ROOT})
set_target_properties(ANALYZE_CODE PROPERTIES EXCLUDE_FROM_ALL TRUE)
endif ()
and later on in the function the custom command is added:
add_custom_command(TARGET
ANALYZE_CODE
PRE_BUILD
COMMAND
${CPPCHECK_EXECUTABLE}
${CPPCHECK_QUIET_ARG}
${CPPCHECK_TEMPLATE_ARG}
${_cppcheck_args}
${_files}
WORKING_DIRECTORY
"${CMAKE_CURRENT_SOURCE_DIR}"
COMMENT
"${_name}_cppcheck: Running cppcheck on target ${_name}..."
VERBATIM)
The problem I'm seeing is that the command is only added for the project that included the file first. I'm not sure why and what is going on. I verified the following using message() commands:
The target is only created once
The add_custom_command is run for every project that calls the function, with proper arguments
But when I actually look at the target in visual studio, only the first include / function call command is added.
If the file is only included without calling the function, no custom commands are added at all.
Desired behavior:
I would like ONE target named "ANALYZE_CODE" to run all commands added by calls to the function.
I.e. if 3 projects include the two lines from above, the target ANALYZE_CODE is created once but 3 custom commands are added to it, one for each project.
It turns out you're somewhat stuck between a rock and a hard place here. The issue I think boils down to a couple of factors.
Firstly, although the docs don't make it clear, add_custom_command(TARGET ...) only works for targets created in the same directory. So the first subproject to call include(cppcheck) is the only one which can effectively add custom commands to the target ANALYZE_CODE.
A workaround for this might seem to be to move all calls to add_cppcheck from their respective subdirectories up to the top-level CMakeLists file.
include(cppcheck)
add_cppcheck(${le_first_project} STYLE POSSIBLE_ERROR FAIL_ON_WARNINGS)
add_cppcheck(${le_second_project} STYLE POSSIBLE_ERROR FAIL_ON_WARNINGS)
...
This isn't a great solution, since these really belong inside their own subdirs. But a bigger issue is that properties on source files only persist in the scope of the CMakeLists.txt in which they are added. This isn't obvious at all, but from the docs for set_source_files_properties:
Source file properties are visible only to targets added in the same directory (CMakeLists.txt).
The innards of the add_cppcheck have the following block of code:
foreach(_source ${_cppcheck_sources})
get_source_file_property(_cppcheck_lang "${_source}" LANGUAGE)
get_source_file_property(_cppcheck_loc "${_source}" LOCATION)
if("${_cppcheck_lang}" MATCHES "CXX")
list(APPEND _files "${_cppcheck_loc}")
endif()
endforeach()
So this is checking that each source file for the given target is designated as a C++ file before adding it to the list of files to be given to cppcheck. If this function is invoked from within the CMakeLists.txt where the target is defined (i.e. the subdir) then the files all have the appropriate property and are correctly added.
However, if the function is called from the parent CMakeLists.txt, the files have lost their properties, and so none are added and cppcheck is passed an empty list!
Now for the possible fixes. There are probably few ways to get out of this hole - I can point to a couple.
You could continue with the option to always call add_cppcheck from the top-level CMake file and avoid using the source files' properties. So the problem codeblock above could be changed to something more like:
set(CxxExtensions .cpp .CPP .cc .CC .cxx .CXX)
foreach(_source ${_cppcheck_sources})
get_filename_component(Extension "${_source}" EXT)
list(FIND CxxExtensions "${Extension}" IsCxxFile)
if(IsCxxFile GREATER -1)
list(APPEND _files "${_source}")
endif()
endforeach()
You could even enforce that the function is only called from the top-level CMakeLists.txt by adding something like this at the start of the function:
if(NOT "${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}")
message(FATAL_ERROR "This can only be called from the top-level CMakeLists.txt")
endif()
The second fix (which I'd personally favour) is to leave the add_cppcheck calls inside the subdirs and have the function add a custom target rather than command. These targets can successfully be applied as dependencies of the top-level target ANALYZE_CODE. So for example, change the add_custom_command to something like:
add_custom_target(ANALYZE_${_name}
${CPPCHECK_EXECUTABLE}
${CPPCHECK_QUIET_ARG}
${CPPCHECK_TEMPLATE_ARG}
${_cppcheck_args}
${_files}
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
COMMENT "ANALYZE_${_name}: Running cppcheck on target ${_name}..."
VERBATIM)
add_dependencies(ANALYZE_CODE ANALYZE_${_name})
set_target_properties(ANALYZE_${_name} PROPERTIES FOLDER "Code Analysis")
This should cause building ANALYZE_CODE to trigger building each of the subordinate ANALYZE_... targets.
It has the downside of "polluting" the solution with a lot of extra targets, but an upside is that you could use these targets in the add_test calls (although this may be a step too far):
# CMake 2.8.0 and newer
add_test(NAME ${_name}_cppcheck_test
COMMAND ${CMAKE_COMMAND}
--build ${CMAKE_BINARY_DIR}
--target ANALYZE_${_name})