GithubHelp home page GithubHelp logo

aminya / project_options Goto Github PK

View Code? Open in Web Editor NEW
320.0 13.0 52.0 17.16 MB

A general-purpose CMake library that provides functions that improve the CMake experience following the best practices.

Home Page: https://aminya.github.io/project_options/

License: MIT License

CMake 97.33% C++ 1.83% CSS 0.04% Dockerfile 0.57% Shell 0.10% C 0.12%
cmake cpp cmake-modules cmake-template starter c conan vcpkg clang-tidy cppcheck

project_options's Introduction

project_options

A general-purpose CMake library that provides functions that improve the CMake experience following the best practices.

documentation

ci

Features

  • project_options:
    • compiler warnings,
    • compiler optimizations (intraprocedural, native),
    • caching (ccache, sccache),
    • sanitizers,
    • static code analyzers (clang-tidy, cppcheck, visual studio, include-what-you-use),
    • document generation (doxygen),
    • test coverage analysis,
    • precompiled headers,
    • build time measurement,
    • unity builds
    • using custom linkers (e.g. lld)
  • package_project: automatic packaging/installation of the project for seamless usage via find_package/target_link through CMake's FetchContent, vcpkg, etc.
  • run_vcpkg: automatic installation of vcpkg and the project dependencies
  • run_conan: automatic installation of conan and the project dependencies
  • dynamic_project_options: a wrapper around project_options to change the options on the fly dynamically
  • target_link_system_libraries and target_include_system_directories: linking/including external dependencies/headers without warnings
  • target_link_cuda: linking Cuda to a target

Documentation

The full documentation is available here:

https://aminya.github.io/project_options/

project_options function

See the project_options() in action in this template repository. cpp_vcpkg_project has prepared all the best practices for a production-ready C++ project.

project and project_options

Here is an example of the usage:

cmake_minimum_required(VERSION 3.20)

# set a default CXX standard for the tools and targets that do not specify them.
# If commented, the latest supported standard for your compiler is automatically set.
# set(CMAKE_CXX_STANDARD 20)

include(FetchContent)
if(CMAKE_VERSION VERSION_GREATER_EQUAL "3.24.0")
  cmake_policy(SET CMP0135 NEW)
endif()

# Add project_options from https://github.com/aminya/project_options
# Change the version in the following URL to update the package (watch the releases of the repository for future updates)
set(PROJECT_OPTIONS_VERSION "v0.35.1")
FetchContent_Declare(
  _project_options
  URL https://github.com/aminya/project_options/archive/refs/tags/${PROJECT_OPTIONS_VERSION}.zip)
FetchContent_MakeAvailable(_project_options)
include(${_project_options_SOURCE_DIR}/Index.cmake)

# install vcpkg dependencies: - should be called before defining project()
run_vcpkg(
    VCPKG_URL "https://github.com/microsoft/vcpkg.git"
    VCPKG_REV "10e052511428d6b0c7fcc63a139e8024bb146032"
)
# Install conan dependencies: - should be called before defining project()
run_conan()

# Set the project name and language
project(myproject LANGUAGES CXX C)

# Build Features
option(FEATURE_TESTS "Enable the tests" OFF)
option(FEATURE_DOCS "Enable the docs" OFF)

# vcpkg test feature
if(FEATURE_TESTS)
  list(APPEND VCPKG_MANIFEST_FEATURES "tests")
endif()

# Enable sanitizers and static analyzers when running the tests
if(FEATURE_TESTS)
  set(ENABLE_CLANG_TIDY "ENABLE_CLANG_TIDY")
  set(ENABLE_CPPCHECK "ENABLE_CPPCHECK")
  set(ENABLE_COVERAGE "ENABLE_COVERAGE")

  check_sanitizers_support(ENABLE_SANITIZER_ADDRESS
                           ENABLE_SANITIZER_UNDEFINED_BEHAVIOR
                           ENABLE_SANITIZER_LEAK
                           ENABLE_SANITIZER_THREAD
                           ENABLE_SANITIZER_MEMORY)
endif()

# Enable doxgen for the docs
if(FEATURE_DOCS)
  set(ENABLE_DOXYGEN "ENABLE_DOXYGEN")
endif()

# Initialize project_options variable related to this project
# This overwrites `project_options` and sets `project_warnings`
# uncomment to enable the options. Some of them accept one or more inputs:
project_options(
      PREFIX "myproject"
      ENABLE_CACHE
      ${ENABLE_CPPCHECK}
      ${ENABLE_CLANG_TIDY}
      ENABLE_VS_ANALYSIS
      # ENABLE_INTERPROCEDURAL_OPTIMIZATION
      # ENABLE_NATIVE_OPTIMIZATION
      ${ENABLE_DOXYGEN}
      ${ENABLE_COVERAGE}
      ${ENABLE_SANITIZER_ADDRESS}
      ${ENABLE_SANITIZER_UNDEFINED_BEHAVIOR}
      # ${ENABLE_SANITIZER_THREAD}
      # ${ENABLE_SANITIZER_MEMORY}
      # ENABLE_CONTROL_FLOW_PROTECTION
      # ENABLE_STACK_PROTECTION
      # ENABLE_OVERFLOW_PROTECTION
      # ENABLE_ELF_PROTECTION
      # ENABLE_RUNTIME_SYMBOLS_RESOLUTION
      # ENABLE_COMPILE_COMMANDS_SYMLINK
      # ENABLE_PCH
      # PCH_HEADERS
      # WARNINGS_AS_ERRORS
      # ENABLE_INCLUDE_WHAT_YOU_USE
      # ENABLE_GCC_ANALYZER
      # ENABLE_BUILD_WITH_TIME_TRACE
      # ENABLE_UNITY
      # LINKER "lld"
)

Then add the executables or libraries to the project:

add_executable(main main.cpp)

# link project_options/warnings
target_link_libraries(main
  PRIVATE myproject_project_options myproject_project_warnings
)

# Find dependencies:
target_find_dependencies(main
  PRIVATE_CONFIG
  fmt
  Eigen3
)

# Link dependencies
target_link_system_libraries(main
  PRIVATE
  fmt::fmt
  Eigen3::Eigen
)

# Package the project
package_project(TARGETS main)
add_library(my_lib "./src/my_lib/lib.cpp")

# link project_options/warnings
target_link_libraries(my_lib
  PRIVATE myproject_project_options myproject_project_warnings
)

# Includes:
target_include_interface_directories(my_lib "${CMAKE_CURRENT_SOURCE_DIR}/include")

# Find dependencies:
target_find_dependencies(my_lib
  PRIVATE_CONFIG
  fmt
  Eigen3
)

# Link dependencies:
target_link_system_libraries(my_lib
  PRIVATE
  fmt::fmt
  Eigen3::Eigen
)

# Package the project
package_project(
  # Note that you must export `myproject_project_options` and `myproject_project_warnings` for `my_lib`
  TARGETS my_lib myproject_project_options myproject_project_warnings
)
add_library(my_header_lib INTERFACE)

# link project_options/warnings
target_link_libraries(my_header_lib
  INTERFACE myproject_project_options myproject_project_warnings
)

# Includes:
target_include_interface_directories(my_header_lib "${CMAKE_CURRENT_SOURCE_DIR}/include")

# Find dependencies:
target_find_dependencies(my_header_lib
  INTERFACE_CONFIG
  fmt
  Eigen3
)

# Link dependencies:
target_link_system_libraries(my_header_lib
  INTERFACE
  fmt::fmt
  Eigen3::Eigen
)

# Package the project
package_project(
  TARGETS my_header_lib myproject_project_options myproject_project_warnings
)

License

This project can be used under the terms of either the MIT license or the Unlicense depending on your choice.

project_options's People

Contributors

abeimler avatar aminya avatar avimalka avatar bogdan-lab avatar bwhitchurch avatar clausklein avatar ddalcino avatar ddassie-texa avatar dk949 avatar feignclaims avatar jmarrec avatar kushal-chandar avatar lambtonr avatar lefticus avatar ltdsauce avatar mous16 avatar project579 avatar sdmg15 avatar sk83rjosh avatar subtixx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

project_options's Issues

Error trying to have multiple projects that use project_options

There's a decent chance this is pure user error and I don't understand how to compose project_options properly, but I'm getting configure-time errors when trying to have multiple projects using project_options, specifically:

[cmake] CMake Error at build/_deps/_project_options-src/src/Index.cmake:125 (add_library):
[cmake]   add_library cannot create target "project_options" because another target
[cmake]   with the same name already exists.  The existing target is an interface
[cmake]   library created in source directory
[cmake]   "/home/mcoding/Projects/project_options_multiple_include_mwe".  See
[cmake]   documentation for policy CMP0002 for more details.

The project structure is like this:

project/
    apps/
        CMakeLists.txt
        main.cpp
    CMakeLists.txt
    external/mylib/
        CMakeLists.txt
        include/mylib
            mylib.hpp

Both project and the submodule mylib use project_options, which explains why cmake thinks project_options is being multiply defined, because both project and mylib do indeed define their own set of project options. Is this a situation where project_options should be defining target names that depend on the project name like ${PROJECT_NAME}_project_options instead of a global name project_options? Or is there some way to have project_options scoped to a namespace like mylib::project_options? Or should only the top-level project be defining project options (using an if TARGET guard before including it) with subprojects modifying the options using dynamic_project_options?

Any guidance here would be appreciated.

Here are the relevant list files for the minimal working example:

Top level CMakeLists.txt:

cmake_minimum_required(VERSION 3.16)

include(FetchContent)
FetchContent_Declare(_project_options URL https://github.com/aminya/project_options/archive/refs/tags/v0.24.1.zip)
FetchContent_MakeAvailable(_project_options)
include(${_project_options_SOURCE_DIR}/Index.cmake)
include(${_project_options_SOURCE_DIR}/src/DynamicProjectOptions.cmake)

project(myproject LANGUAGES CXX C)

dynamic_project_options()

add_subdirectory(external/mylib)

add_subdirectory(apps)

apps/CMakeLists.txt

add_executable(main main.cpp)
target_link_libraries(main PRIVATE project_options project_warnings)

target_link_system_libraries(
  main
  PRIVATE mylib
)

external/mylib/CMakeLists.txt

cmake_minimum_required(VERSION 3.16)

include(FetchContent)
FetchContent_Declare(_project_options URL https://github.com/aminya/project_options/archive/refs/tags/v0.24.1.zip)
FetchContent_MakeAvailable(_project_options)
include(${_project_options_SOURCE_DIR}/Index.cmake)
include(${_project_options_SOURCE_DIR}/src/DynamicProjectOptions.cmake)

project(mylib LANGUAGES CXX C)

dynamic_project_options()

add_library(mylib INTERFACE)
target_link_libraries(mylib INTERFACE project_options project_warnings)

set(INCLUDE_DIR "include") 
target_include_directories(mylib INTERFACE "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/${INCLUDE_DIR}>"
                                          "$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>")

error: PCH file built from a different branch ((clang-1316.0.21.2)) than the compiler () [clang-diagnostic-error]

task: [test_release] cmake --build ./test/build --config Release
[2/6] Building CXX object CMakeFiles/lib2.dir/Release/src/mylib2/lib.cpp.o
/Users/clausklein/cmake/cmakelib/test/src/mylib2/lib.cpp:22:47: warning: 10 is a magic number; consider replacing it with a named constant [cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers]
  auto eigen_vec = Eigen::VectorXd::LinSpaced(10, 0, 1);
                                              ^
Checking /Users/clausklein/cmake/cmakelib/test/src/mylib2/lib.cpp ...
Checking /Users/clausklein/cmake/cmakelib/test/src/mylib2/lib.cpp: FMT_LOCALE=1;CMAKE_INTDIR="Release";NDEBUG=1...
[4/6] Building CXX object CMakeFiles/main.dir/Release/cmake_pch.hxx.pch
Checking /Users/clausklein/cmake/cmakelib/test/build/CMakeFiles/main.dir/cmake_pch.hxx.cxx ...
Checking /Users/clausklein/cmake/cmakelib/test/build/CMakeFiles/main.dir/cmake_pch.hxx.cxx: FMT_LOCALE=1;CMAKE_INTDIR="Release";NDEBUG=1...
[5/6] Building CXX object CMakeFiles/main.dir/Release/src/main/main.cpp.o
FAILED: CMakeFiles/main.dir/Release/src/main/main.cpp.o 
/usr/local/Cellar/cmake/3.22.1/bin/cmake -E __run_co_compile --launcher=/usr/local/bin/ccache --tidy="/usr/local/opt/llvm/bin/clang-tidy;-extra-arg=-Wno-unknown-warning-option;-extra-arg=-std=c++20;--extra-arg-before=--driver-mode=g++" --cppcheck="/usr/local/bin/cppcheck;--template=gcc;--enable=style,performance,warning,portability;--inline-suppr;--suppress=internalAstError;--suppress=unmatchedSuppression;--inconclusive;--std=c++20" --source=/Users/clausklein/cmake/cmakelib/test/src/main/main.cpp -- /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -DFMT_LOCALE -DCMAKE_INTDIR=\"Release\" -isystem /Users/clausklein/cmake/cmakelib/test/build/vcpkg_installed/x64-osx/include -isystem /Users/clausklein/cmake/cmakelib/test/build/vcpkg_installed/x64-osx/include/eigen3 -O3 -DNDEBUG -flto=thin -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -fcolor-diagnostics -march=native --coverage -O0 -g -Wall -Wextra -Wshadow -Wnon-virtual-dtor -Wold-style-cast -Wcast-align -Wunused -Woverloaded-virtual -Wpedantic -Wconversion -Wsign-conversion -Wnull-dereference -Wdouble-promotion -Wformat=2 -Wimplicit-fallthrough -std=c++2a -Winvalid-pch -Xclang -include-pch -Xclang /Users/clausklein/cmake/cmakelib/test/build/CMakeFiles/main.dir/Release/cmake_pch.hxx.pch -Xclang -include -Xclang /Users/clausklein/cmake/cmakelib/test/build/CMakeFiles/main.dir/Release/cmake_pch.hxx -MD -MT CMakeFiles/main.dir/Release/src/main/main.cpp.o -MF CMakeFiles/main.dir/Release/src/main/main.cpp.o.d -o CMakeFiles/main.dir/Release/src/main/main.cpp.o -c /Users/clausklein/cmake/cmakelib/test/src/main/main.cpp
error: PCH file built from a different branch ((clang-1316.0.21.2)) than the compiler () [clang-diagnostic-error]
1 error generated.
Error while processing /Users/clausklein/cmake/cmakelib/test/src/main/main.cpp.
Found compiler error(s).
ninja: build stopped: subcommand failed.
task: Failed to run task "test_install": task: Failed to run task "test_release": exit status 1
bash-3.2$ find . -name '*.pch'
./test/build/CMakeFiles/main.dir/Release/cmake_pch.hxx.pch
bash-3.2$ which gcc
/usr/bin/gcc
bash-3.2$ gcc --version
Apple clang version 13.1.6 (clang-1316.0.21.2)
Target: x86_64-apple-darwin21.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
bash-3.2$ 


<!-- POLAR PLEDGE BADGE START -->
## Upvote & Fund

- I am using [Polar.sh](https://polar.sh/aminya) so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

- Thank you in advance for helping prioritize & fund our backlog.

<a href="https://polar.sh/aminya/project_options/issues/107">
<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/aminya/project_options/issues/107/pledge.svg?darkmode=1">
  <img alt="Fund with Polar" src="https://polar.sh/api/github/aminya/project_options/issues/107/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->

CMAKE option warnings and errors not consistent (or documented)

I noticed that not all cmake warnings are turned into errors when the variable WARNING_MESSAGE is set to SEND_ERROR, hence WARNINGS_AS_ERRORS enabled.

For example a missing clang-tidy will produce an error if the corresponding option is set (see StaticAnalyzer.cmake:32).
On the other hand a missing Sanitizer is always producing a warning (see Sanitizers.cmake:27).
Same goes for a missing ccache executable (see cache.cmake:29).

I cannot find any explantation why those are treated different, which kind of confuses me.

Would it be possible to add comments why some do not use the WARNING_MESSAGE variable, if that had been done on purpose?
Which seems the case at least for clang-tidy if i correctly understand #30.

Enable StaticAnalyzers for C

Currently only CXX are supported by cppcheck, clang-tidy, and include-what-you-use. It would be great to have them enabled for C as well.

  • Set C standard: #65
  • Clang-tidy for C #78
  • Cppecheck for C #77

Need VCPKG_FORCE_SYSTEM_BINARIES env for installing vcpkg dependencies on ARM

When installing libraries, vcpkg raises this error:

Environment variable VCPKG_FORCE_SYSTEM_BINARIES must be set on arm, s390x, and ppc64le platforms.

Ref: https://github.com/microsoft/vcpkg-tool/blob/2022-02-11/src/vcpkg.cpp#L61

Originally, I was hoping to use the detect_architecture() function in VCEnvironment.cmake to solve this problem, but it turned out detect_architecture cannot detect the ARCH on ARM. Here is a similar issue: microsoft/vcpkg#17832

For cmake < 3.17, CMAKE_HOST_SYSTEM_PROCESSOR uses the command uname -p to get the result but it simply returns "unknown" on ARM: https://cmake.org/cmake/help/v3.16/variable/CMAKE_HOST_SYSTEM_PROCESSOR.html

An unrelated suggestion is that I would like to move the inclusion of Utilities.cmake outside of the file VCEnvironment.cmake, since the functions in Utilities.cmake are no longer exclusively used by that single file.

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

CUDA compilation not supported

When I specify project as mixed C / C++ / CUDA:
project(my_project) LANGUAGES CUDA CXX C)

the compilation of .cu files fails:

cd ... && /usr/local/cuda/bin/nvcc  -DPROJECT_ROOT=\"...\" -g -Xcompiler=-fPIC   -std=c++17 -Wall -Wextra -Wshadow -Wnon-virtual-dtor -Wold-style-cast -Wcast-align -Wunused -Woverloaded-virtual -Wpedantic -Wconversion -Wsign-conversion -Wnull-dereference -Wdouble-promotion -Wformat=2 -Werror -Wmisleading-indentation -Wduplicated-cond -Wduplicated-branches -Wlogical-op -Wuseless-cast -x cu -c kernels.cu -o kernels.cu.o
nvcc fatal   : Value '-Wmisleading-indentation' is not defined for option 'Werror'

Static analyzer: suppress warning for 3rd-party/system libs

Is it possible to exclude targets or 3rd-party libs from the static analyzer ?

Root Project

option(ENABLE_TESTING "Enable the tests" ${PROJECT_IS_TOP_LEVEL})
if(ENABLE_TESTING)
  set(ENABLE_CLANG_TIDY "ENABLE_CLANG_TIDY")
  set(ENABLE_CPPCHECK "ENABLE_CPPCHECK")
  set(ENABLE_COVERAGE "ENABLE_COVERAGE")

  if(NOT "${CMAKE_SYSTEM_NAME}" STREQUAL "Windows")
    set(ENABLE_SANITIZER_ADDRESS "ENABLE_SANITIZER_ADDRESS")
    set(ENABLE_SANITIZER_UNDEFINED_BEHAVIOR "ENABLE_SANITIZER_UNDEFINED_BEHAVIOR")
  else()
    # or it is MSVC and has run vcvarsall
    string(FIND "$ENV{PATH}" "$ENV{VSINSTALLDIR}" index_of_vs_install_dir)
    if(MSVC AND "${index_of_vs_install_dir}" STREQUAL "-1")
      set(ENABLE_SANITIZER_ADDRESS "ENABLE_SANITIZER_ADDRESS")
    endif()
  endif()
endif()

# defaulted_project_options sets recommended defaults and provides user and developer
# modes and full GUI support for choosing options at configure time
# for more flexibility, look into project_options() macro
# Initialize project_options variable related to this project
# This overwrites `project_options` and sets `project_warnings`
# uncomment the options to enable them:
dynamic_project_options(
  ENABLE_CACHE
  ${ENABLE_CPPCHECK}
  ${ENABLE_CLANG_TIDY}
  ENABLE_VS_ANALYSIS
  ${ENABLE_COVERAGE}
  ${ENABLE_SANITIZER_ADDRESS}
  ${ENABLE_SANITIZER_UNDEFINED_BEHAVIOR}
  # Note: PCH is disabled by default in developer mode because these headers become
  # globally included and they can mask other errors
  PCH_HEADERS
  # This is a list of headers to pre-compile, here are some common ones
  <vector>
  <string>
  <utility>
  <array>
  <algorithm>
  <concepts>
  CPPCHECK_OPTIONS
  --enable=style,performance,warning,portability
  --inline-suppr
  # We cannot act on a bug/missing feature of cppcheck
  --suppress=cppcheckError
  --suppress=internalAstError
  # if a file does not have an internalAstError, we get an unmatchedSuppression error
  --suppress=unmatchedSuppression
  --suppress=passedByValue
  --suppress=syntaxError
  --inconclusive
)
target_compile_features(project_options INTERFACE cxx_std_${CMAKE_CXX_STANDARD})

Add lib cmake

# get raylib from github and build as static lib
cpmaddpackage(
    NAME
    raylib
    GIT_TAG
    4.0.0
    GITHUB_REPOSITORY
    raysan5/raylib
    OPTIONS
    "BUILD_SHARED_LIBS OFF")
if(NOT MSVC)
  # don't error on implicit declarations, which are invalid in C99 but commonly used
  target_compile_options(raylib PRIVATE -Wno-error=implicit-function-declaration)
endif()

Project cmake

add_library(engine STATIC)
# more library options
target_link_libraries(engine PRIVATE project_warnings project_options)

# add 3rd-party libs as system libs
target_link_system_libraries(engine PUBLIC raylib)

Warnings from raylib

[2/127] Building C object _deps/raylib-build/raylib/CMakeFiles/raylib.dir/rtextures.c.o
Checking cmake-build-debug/_deps/raylib-src/src/rtextures.c ...
Checking cmake-build-debug/_deps/raylib-src/src/rtextures.c: GRAPHICS_API_OPENGL_33=1;PLATFORM_DESKTOP=1...
cmake-build-debug/_deps/raylib-src/src/external/stb_image.h:7013:37: warning: Array 'signature[8]' accessed at index 10, which is out of bounds. [arrayIndexOutOfBounds]
      if (stbi__get8(s) != signature[i])
                                    ^
cmake-build-debug/_deps/raylib-src/src/external/stb_image_write.h:1378:16: warning: Array index 'i' is used before limits check. [arrayIndexThenCheck]
      for (; DU[i]==0 && i<=end0pos; ++i) {
               ^
cmake-build-debug/_deps/raylib-src/src/external/stb_image.h:4316:23: warning: Condition 'c==18' is always true [knownConditionTrueFalse]
         } else if (c == 18) {
                      ^
cmake-build-debug/_deps/raylib-src/src/external/stb_image.h:4314:23: note: Assuming that condition 'c==17' is not redundant
         } else if (c == 17) {
                      ^
cmake-build-debug/_deps/raylib-src/src/external/stb_image.h:4305:22: note: Assuming that condition 'c>=19' is not redundant
      if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");

environment

  • OS: Linux
  • Compiler: gcc 11
  • Cmake: cmake 3.22.1
  • IDE: CLion

Improve documentation

  • add a website for the documentation #198
  • add instructions for making an executable #58
  • add instructions for making a header-only library #58
  • add instructions for making a normal library #58
  • add instructions for using doxygen-docs target
  • add instructions for using sanitizers (especially on windows)
  • adding more examples for using the options:
    • using PCH headers
    • using coverage
    • overriding compiler warnings,
    • adding more warnings
    • removing certain warnings for certain targets
  • documenting the individual functions (e.g. enable_doxygen) in case more control is needed
  • add documentation for cross-compilation

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

Problem with presets and coverage (No such file or directory)

I don't know if this problem is related to this project, or if the problem is related to CMake or another tool. Anyway, I wrote here, because I am taking this project, and when I add ENABLE_COVERAGE, the coverage, for example, Experimental build target failed. If ENABLE_COVERAGE is off, the coverage step is skipped. This target is related and documented in CTest.

For easier repeating the problem and knowing what I am talking about, I am trying also in FTXUI template from cpp-best-practices, because I know @lefticus is a contributor of Ftxui and project_options and this will be the perfect project for repeating the problem. In this project, I just add ENABLE_COVERAGE in dynamic_project_options and run preset GCC Debug and target Experimental. Is the same problem if I am using different preset configurations. It is also the same if I change from dynamic_project_options to project_options. I am using VSCode and docker all the same setup is defined in the project.

The output of unixlike-clang-debug - Experimental in the project ftxui_template

[cmake] -- Generating done
[cmake] -- Build files have been written to: /workspaces/ftxui_template-main/out/build/unixlike-clang-debug
[build] Starting build
[proc] Executing command: /usr/bin/cmake --build /workspaces/ftxui_template-main/out/build/unixlike-clang-debug --target Experimental
[build] [0/1] cd /workspaces/ftxui_template-main/out/build/unixlike-clang-debug && /usr/bin/ctest -D Experimental
[build]    Site: 06bc8536816d
[build]    Build name: Linux-clang++
[build] Create new tag: 20220728-0821 - Experimental
[build] Configure project
[build]    Each . represents 1024 bytes of output
[build]     .... Size of output: 3K
[build] Build project
[build]    Each symbol represents 1024 bytes of output.
[build]    '!' represents an error and '*' a warning.
[build]     .. Size of output: 1K
[build]    0 Compiler errors
[build]    0 Compiler warnings
[build] Test project /workspaces/ftxui_template-main/out/build/unixlike-clang-debug
[build]     Start 1: unittests.Factorials are computed
[build] 1/5 Test #1: unittests.Factorials are computed ..........................   Passed    0.07 sec
[build]     Start 2: constexpr.Factorials are computed with constexpr
[build] 2/5 Test #2: constexpr.Factorials are computed with constexpr ...........   Passed    0.07 sec
[build]     Start 3: relaxed_constexpr.Factorials are computed with constexpr
[build] 3/5 Test #3: relaxed_constexpr.Factorials are computed with constexpr ...   Passed    0.06 sec
[build]     Start 4: cli.has_help
[build] 4/5 Test #4: cli.has_help ...............................................   Passed    0.28 sec
[build]     Start 5: cli.version_matches
[build] 5/5 Test #5: cli.version_matches ........................................   Passed    0.31 sec
[build] 
[build] 100% tests passed, 0 tests failed out of 5
[build] 
[build] Total Test time (real) =   0.90 sec
[build] Performing coverage
[build]    Processing coverage (each . represents one file):
[build] No such file or directory
[build] Problem running coverage on file: /workspaces/ftxui_template-main/out/build/unixlike-clang-debug/src/CMakeFiles/intro.dir/main.cpp.gcda
[build] Command produced error: No such file or directory
[build]  Cannot find any coverage files. Ignoring Coverage request.

The problem is in /workspaces/ftxui_template-main/out/build/unixlike-clang-debug/src/CMakeFiles/intro.dir exist .gcda, .gcno and .o file.

So my question is if I am doing something wrong? I'm new in CMake preset and with this project. Also, it seems like something is not well set for CTest when the coverage is enabled. I have the same problem in my project as in Ftxui.
Also, any help on how to investigate, test, and fix the problem will be very pleasant. Thank you for all your tips and investigations.

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

Adding an option for not adding the default Conan remotes

Currently, the conan section forces the addition of both the conan-center-index and bincrafters remotes by default. Even though the comments state that we can remove remotes, I can't figure out how to do it without calling conan through add_custom_command or something like that.

The thing with adding bincrafters by default is that it sometimes complains about some env variables not defined. For that reason, and the fact that not everybody is going to use dependencies from the bincrafters remote, I propose to remove its addition and let the users decide whether they want to add it or not. Maybe a wrapper around conan_add_remote could be added to ease the job for users.

Upvote & Fund

@aminya is using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

Thank you in advance for helping prioritize & fund our backlog!


Fund with Polar

Warning instead of error if clang-tidy and cppcheck are not installed?

I think we should enable clang-tidy and cppcheck by default, but instead of throwing errors if they are missing, we can give warnings.

The use case is that I want to enable clang-tidy and cppcheck on my own machine because I am sure they are installed, but I want to also allow the users to build the project even if they do not have these.

We can still allow this to error out if WARNING_AS_ERRORS is enabled.

Adding more compiler warnings by default

There are other Clang warnings that we have not added. We have already enabled the most pedantic ones, so I think adding these will complete the list and would be beneficial.

-Wformat-overflow
-Wformat-nonliteral
-Wformat-truncation=2
-fno-common
-Wcast-qual
-Wdeprecated
-Wmissing-declarations
-Wmissing-prototypes
-Wnested-externs
-Wold-style-definition
-Wpointer-arith
-Wsign-compare
-Wstrict-prototypes
-Wundef
-Wwrite-strings

https://clang.llvm.org/docs/DiagnosticsReference.html

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

DynamicProjectOptions example is incorrect

The dynamic project options example in the readme does not work for me. I've debugged that I must define setting defaults before including DynamicProjectOptions.cmake.

For example, in this case ccache will always be enabled even though the default should be OFF:

include(${_project_options_SOURCE_DIR}/src/DynamicProjectOptions.cmake)
set(ENABLE_CACHE_DEFAULT OFF)
dynamic_project_options()

This is resolved if you define the setting before including the macro:

set(ENABLE_CACHE_DEFAULT OFF)
include(${_project_options_SOURCE_DIR}/src/DynamicProjectOptions.cmake)
dynamic_project_options()

I don't know if this behavior can be changed, so that the setting will always be correctly overridden by the dynamic_project_options macro. But I do think the example shown in the readme should be fixed.

Allow the user to use a conan profile

Sometimes it can be challenging to convince Conan to use the settings that you want it to. Conan allows users to use a profile to provide fine grain control over what settings Conan uses. See Conan instructions for using Emscripten for a common use case for Conan profiles.

Currently, project_options forces the user to use conan_cmake_autodetect() to determine settings automatically. A Conan profile, if desired, should replace this step, and allow the user to choose all of these settings explicitly.

What I would like: I think that a user should be allowed to pass a Conan profile as an argument to the project_options function. When that variable is not empty, project_options should skip conan_cmake_autodetect(), and call conan_cmake_install() with the argument PROFILE ${PATH_TO_CONAN_PROFILE}.

package_project() does not normalize the install paths before printing

my CMakeLists.txt contains this:

# ---- Create library ----

# Note: for header-only libraries change all PUBLIC flags to INTERFACE and create an interface
# target: add_library(${PROJECT_NAME} INTERFACE)
add_library(${PROJECT_NAME} ${headers} ${sources})
add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_20)

# being a cross-platform target, we enforce standards conformance on MSVC
target_compile_options(${PROJECT_NAME} PRIVATE "$<$<COMPILE_LANG_AND_ID:CXX,MSVC>:/permissive->")

# Link dependencies
target_link_libraries(${PROJECT_NAME} PUBLIC fmt::fmt)

# FIXME: should be PRIVATE! CK
target_link_libraries(${PROJECT_NAME} PUBLIC project_warnings project_options)

# target_include_directories with the SYSTEM modifier will request the compiler
# to omit warnings from the provided paths, if the compiler supports that
target_include_directories(
  ${PROJECT_NAME} SYSTEM PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
                                $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)

if(CMAKE_SKIP_INSTALL_RULES)
  return()
endif()

# ---- Create an installable target ----
# this allows users to install and find the library via `find_package()`.

# Add other targets that you want installe here. Or be default we just package
# all targets recursively found for the current folder if not specified.
package_project(
  NAME ${PROJECT_NAME}
  TARGETS ${PROJECT_NAME} project_options project_warnings
  PUBLIC_INCLUDES ${PROJECT_SOURCE_DIR}/include
  PUBLIC_DEPENDENCIES_CONFIGURED "fmt 8.1.1"
  # FIXME: not yet used! PRIVATE_DEPENDENCIES_CONFIGURED project_options project_warnings
)
cmake -B ./build-ModernCmakeStarter-Debug -S /Users/clausklein/Workspace/cpp/ModernCmakeStarter/all -D OPT_ENABLE_COVERAGE=NO -DOPT_WARNINGS_AS_ERRORS=NO
-- CPM: adding package [email protected] (v3.0.0 at /Users/clausklein/.cache/CPM/cxxopts/0c1df694f5ab3306e541038e6a2ed62926062894)
-- CPM: adding package greeter@ (/Users/clausklein/Workspace/cpp/ModernCmakeStarter/standalone/..)
-- CPM: greeter: adding package [email protected] (v0.20.0 at /Users/clausklein/.cache/CPM/project_options/f4f28e0d6a43eb4247d834f6b906d21040cf1ef9)
-- CPM: greeter: adding package [email protected] (v1.8.0 at /Users/clausklein/.cache/CPM/packageproject.cmake/987b02f8a9fe04de3c43e0e7a1afbb29c87adc5e)
-- Module support is disabled.
-- Version: 8.1.1
-- Build type: Debug
-- CXX_STANDARD: 20
-- Required features: cxx_variadic_templates
-- CPM: greeter: adding package [email protected] (8.1.1 at /Users/clausklein/.cache/CPM/fmt/15c05aa781ab44fa13a906fe5737c1d14e5edee9)
-- Developer mode is ON. For production, use `-DENABLE_DEVELOPER_MODE:BOOL=OFF`. Building the project for the developer...
-- The default CMAKE_C_STANDARD used by external targets and tools is not set yet. Using the latest supported C standard that is 90
-- /usr/local/bin/ccache found and enabled
-- CPM: adding package [email protected] (v2.4.8 at /Users/clausklein/.cache/CPM/doctest/367f22d2dff85570a9f727b99741f9e40b17df46)
-- CPM: adding package [email protected] (v1.7.3 at /Users/clausklein/.cache/CPM/format.cmake/17e103764947115e78d95ecc29c4bee54dc64e08)
-- CPM: adding package Greeter@ (/Users/clausklein/Workspace/cpp/ModernCmakeStarter/test/..)
-- CPM: adding package m.css@0 (a0d292ec311b97fefd21e93cdefb60f88d19ede6 at /Users/clausklein/.cache/CPM/m.css/23b42fe3166cf5c34c25c267ae0664557edd2200)
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/clausklein/Workspace/cpp/ModernCmakeStarter/build-ModernCmakeStarter-Debug
DESTDIR=/Users/clausklein/Workspace/cpp/stage cmake --install ./build-ModernCmakeStarter-Debug --prefix /usr
-- Install configuration: "Debug"
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/cmake/cxxopts/cxxopts-config.cmake
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/cmake/cxxopts/cxxopts-config-version.cmake
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/cmake/cxxopts/cxxopts-targets.cmake
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/cxxopts.hpp
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/pkgconfig/cxxopts.pc
-- Installing: /Users/clausklein/Workspace/cpp/stage/usr/lib/libfmtd.a
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/cmake/fmt/fmt-config.cmake
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/cmake/fmt/fmt-config-version.cmake
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/cmake/fmt/fmt-targets.cmake
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/cmake/fmt/fmt-targets-debug.cmake
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/args.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/chrono.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/color.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/compile.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/core.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/format.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/format-inl.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/locale.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/os.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/ostream.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/printf.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/ranges.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/include/fmt/xchar.h
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/lib/pkgconfig/fmt.pc
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/.//include
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/.//include/greeter
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/.//include/greeter/greeter.h
-- Installing: /Users/clausklein/Workspace/cpp/stage/usr/lib/libgreeter.a
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/share/greeter/greeterConfigVersion.cmake
-- Up-to-date: /Users/clausklein/Workspace/cpp/stage/usr/share/greeter/greeterConfig.cmake
-- Old export file "/Users/clausklein/Workspace/cpp/stage/usr/share/greeter/greeterTargets.cmake" will be replaced.  Removing files [/Users/clausklein/Workspace/cpp/stage/usr/share/greeter/greeterTargets-debug.cmake].
-- Installing: /Users/clausklein/Workspace/cpp/stage/usr/share/greeter/greeterTargets.cmake
-- Installing: /Users/clausklein/Workspace/cpp/stage/usr/share/greeter/greeterTargets-debug.cmake
-- Installing: /Users/clausklein/Workspace/cpp/stage/usr/share/greeter/usage
-- # The package greeter provides the following CMake targets:

    find_package(greeter CONFIG REQUIRED)
    target_link_libraries(main PRIVATE  greeter::greeter greeter::project_options greeter::project_warnings)
  
bash-3.2$ 

This installed CMake config packages contains:

# Create imported target greeter::greeter
add_library(greeter::greeter STATIC IMPORTED)

set_target_properties(greeter::greeter PROPERTIES
  INTERFACE_COMPILE_FEATURES "cxx_std_20"
  INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
  INTERFACE_LINK_LIBRARIES "fmt::fmt;greeter::project_warnings;greeter::project_options"
  INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "include"
)

# Create imported target greeter::project_options
add_library(greeter::project_options INTERFACE IMPORTED)

set_target_properties(greeter::project_options PROPERTIES
  INTERFACE_COMPILE_FEATURES "cxx_std_20"
  INTERFACE_COMPILE_OPTIONS "-fsanitize=address,undefined"
  INTERFACE_LINK_OPTIONS "-fsanitize=address,undefined"
)

# Create imported target greeter::project_warnings
add_library(greeter::project_warnings INTERFACE IMPORTED)

set_target_properties(greeter::project_warnings PROPERTIES
  INTERFACE_COMPILE_OPTIONS "\$<\$<COMPILE_LANGUAGE:CXX>:-Wall;-Wextra;-Wshadow;-Wnon-virtual-dtor;-Wold-style-cast;-Wcast-align;-Wunused;-Woverloaded-virtual;-Wpedantic;-Wconversion;-Wsign-conversion;-Wnull-dereference;-Wdouble-promotion;-Wformat=2;-Wimplicit-fallthrough>;\$<\$<COMPILE_LANGUAGE:C>:-Wall;-Wextra;-Wshadow;-Wcast-align;-Wunused;-Wpedantic;-Wconversion;-Wsign-conversion;-Wnull-dereference;-Wdouble-promotion;-Wformat=2;-Wimplicit-fallthrough>;\$<\$<COMPILE_LANGUAGE:CUDA>:-Wall;-Wextra;-Wunused;-Wconversion;-Wshadow>"
)
``


<!-- POLAR PLEDGE BADGE START -->
## Upvote & Fund

- I am using [Polar.sh](https://polar.sh/aminya) so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

- Thank you in advance for helping prioritize & fund our backlog.

<a href="https://polar.sh/aminya/project_options/issues/117">
<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/api/github/aminya/project_options/issues/117/pledge.svg?darkmode=1">
  <img alt="Fund with Polar" src="https://polar.sh/api/github/aminya/project_options/issues/117/pledge.svg">
</picture>
</a>
<!-- POLAR PLEDGE BADGE END -->

Add toolchain support

Add function to setup -DCMAKE_TOOLCHAIN_FILE/-DVCPKG_TOOLCHAIN_FILE and include() toolchain via -DOPT_TARGET_TRIPLET:STRING=x64-mingw-dynamic option.

Example:

project_options(
   TARGET_TRIPLET "x64-mingw-dynamic"
)

or with cmake arguments:

# for custom toolchains
cmake ... -DOPT_TOOLCHAIN_FILE:STRING="..." -DOPT_TARGET_TRIPLET:STRING="..."
## setup vcpkg and more

# use project_options toolchains
cmake ... -DOPT_TARGET_TRIPLET:STRING="..."
## setup vcpkg and more

# use vcpkg arguments
cmake ... -DVCPKG_CHAINLOAD_TOOLCHAIN_FILE="..." -DVCPKG_TARGET_TRIPLET="..."
## read vcpkg triplet and set OPT_TARGET_TRIPLET etc.

Notes

  • Cross compiler must setup by user
  • Maybe addition arguments must be pass for cross-compiler root path or other paths like Android NDK, emscripten SDK (emsdk), ...

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

Allow to specify a GitHub mirror for dependencies

Currently the dependencies (fargs, ycm, conan) are fetched from github. Unfortunately, this does not work in environments where github is only accessible via a mirror. Would it be possible to somehow parameterize the github mirror for these dependencies?

Or is it only possible to appy a patch to replace the dependent urls when calling FetchContent_Declare?

GCC warning and optimization flags could be used by clang when include-what-you-use is enabled

I see the following messages raised when include-what-you-use is running during cmake build:

warning: optimization flag '-fno-fat-lto-objects' is not supported
error: unknown warning option '-Wduplicated-cond' [-Werror,-Wunknown-warning-option]
error: unknown warning option '-Wduplicated-branches' [-Werror,-Wunknown-warning-option]
error: unknown warning option '-Wlogical-op'; did you mean '-Wlong-long'? [-Werror,-Wunknown-warning-option]
error: unknown warning option '-Wuseless-cast' [-Werror,-Wunknown-warning-option]

These warnings are set by CompilerWarnings.cmake.

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

CMake's `FetchContent` fails in the "untar" step on Windows

It seems to be a a problem on Windows Cmake (i have no problem on Mac or Linux) but any way I open an issue if you know a turn-around....
-- extracting... [tar xfz]
CMake Error: Problem with archive_write_finish_entry(): Can't restore time
CMake Error: Problem extracting tar: K:/Project/_deps/_project_options-subbuild/_project_options-populate-prefix/src/v0.18.1.zip
-- extracting... [error clean up]
CMake Error at _project_options-subbuild/_project_options-populate-prefix/src/_project_options-populate-stamp/extract-_project_options-populate.cmake:33 (message):
error: extract of
'K:/Project/_deps/_deps/_project_options-subbuild/_project_options-populate-prefix/src/v0.18.1.zip'
failed

Since v0.22.0, Visual Studio 2022 can't generate cmake cahce.

I'm using CMake Project in Visual Studio 2022.
If I upgrade 'porject_options' to 0.22.0 from 0.21.1, it reports below error and cmake cache generation has failed.

1> [CMake] -- Using Windows MSVC toolchain
1> [CMake] -- Setting CXX/C compiler to C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe
1> [CMake] -- Running `C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC/Auxiliary/Build/vcvarsall.bat x64` to set up the MSVC environment
1> [CMake] ERROR: The system was unable to find the specified registry key or value.
1> [CMake] -- Using Windows MSVC toolchain
1> [CMake] -- Setting CXX/C compiler to C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe
1> [CMake] -- Running `C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC/Auxiliary/Build/vcvarsall.bat x64` to set up the MSVC environment
1> [CMake] ERROR: The system was unable to find the specified registry key or value.

Mingw: `mingw_unicode()` doesn't always fix undefined references to WinMain

aminya/cpp_vcpkg_project#9

I have written a macro in project_options to try to fix the WinMain issue in MinGW. But adding -municode as a compile option doesn't fix the issue. Adding it as a link option causes linking to the fail with undefined reference to wWinMain. Other compilers don't need such flags, and I am not sure why we should do this for MinGW.

macro(mingw_unicode)
  is_mingw(_is_mingw)
  if(${_is_mingw})
    include(CheckCXXCompilerFlag)
    check_cxx_compiler_flag("-municode" _cxx_supports_municode)
    if(${_cxx_supports_municode})
      message(STATUS "Enabling Unicode for MinGW in the current project to fix undefined references to WinMain")
      add_compile_definitions("UNICODE" "_UNICODE")
      add_compile_options("-municode")
    endif()
  endif()
endmacro()

https://github.com/aminya/cpp_vcpkg_project/runs/6542106054?check_suite_focus=true#step:6:203

[6/18] Linking CXX executable my_exe\test\Debug\my_exe_helpers_tests.exe
FAILED: my_exe/test/Debug/my_exe_helpers_tests.exe 
cmd.exe /C "cd . && C:\Users\runneradmin\gcc\mingw64\bin\g++.exe -g  my_exe/test/CMakeFiles/my_exe_helpers_tests.dir/Debug/tests.cpp.obj -o my_exe\test\Debug\my_exe_helpers_tests.exe -Wl,--out-implib,my_exe\test\Debug\libmy_exe_helpers_tests.dll.a -Wl,--major-image-version,0,--minor-image-version,0  vcpkg_installed/x64-mingw-static/debug/lib/libfmtd.a  --coverage  -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
c:/users/runneradmin/gcc/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: c:/users/runneradmin/gcc/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.3.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text+0x46): undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status
[7/18] Linking CXX executable my_lib\test\Debug\my_lib_tests.exe
FAILED: my_lib/test/Debug/my_lib_tests.exe my_lib/test/my_lib_tests_tests-84286ba.cmake D:/a/cpp_vcpkg_project/cpp_vcpkg_project/build/my_lib/test/my_lib_tests_tests-84286ba.cmake 
cmd.exe /C "cd . && C:\Users\runneradmin\gcc\mingw64\bin\g++.exe -g  my_lib/test/CMakeFiles/my_lib_tests.dir/Debug/tests.cpp.obj -o my_lib\test\Debug\my_lib_tests.exe -Wl,--out-implib,my_lib\test\Debug\libmy_lib_tests.dll.a -Wl,--major-image-version,0,--minor-image-version,0  my_lib/Debug/libmy_lib.a  --coverage  vcpkg_installed/x64-mingw-static/debug/lib/libfmtd.a  -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cmd.exe /C "cd /D D:\a\cpp_vcpkg_project\cpp_vcpkg_project\build\my_lib\test && C:\Users\runneradmin\cmake\cmake-3.23.1-windows-x86_64\bin\cmake.exe -D TEST_TARGET=my_lib_tests -D TEST_EXECUTABLE=D:/a/cpp_vcpkg_project/cpp_vcpkg_project/build/my_lib/test/Debug/my_lib_tests.exe -D TEST_EXECUTOR= -D TEST_WORKING_DIR=D:/a/cpp_vcpkg_project/cpp_vcpkg_project/build/my_lib/test -D TEST_SPEC= -D TEST_EXTRA_ARGS= -D TEST_PROPERTIES= -D TEST_PREFIX= -D TEST_SUFFIX= -D TEST_LIST=my_lib_tests_TESTS -D TEST_REPORTER=xml -D TEST_OUTPUT_DIR= -D TEST_OUTPUT_PREFIX= -D TEST_OUTPUT_SUFFIX= -D CTEST_FILE=D:/a/cpp_vcpkg_project/cpp_vcpkg_project/build/my_lib/test/my_lib_tests_tests-84286ba.cmake -P D:/a/cpp_vcpkg_project/cpp_vcpkg_project/build/vcpkg_installed/x64-mingw-static/share/catch2/CatchAddTests.cmake""
c:/users/runneradmin/gcc/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: c:/users/runneradmin/gcc/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.3.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text+0x46): undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status
[8/18] Building CXX object my_header_lib/test/constexpr/CMakeFiles/my_header_lib_relaxed_constexpr_tests.dir/Debug/constexpr_tests.cpp.obj
Checking D:\a\cpp_vcpkg_project\cpp_vcpkg_project\my_header_lib\test\constexpr\constexpr_tests.cpp ...
Checking D:\a\cpp_vcpkg_project\cpp_vcpkg_project\my_header_lib\test\constexpr\constexpr_tests.cpp: CATCH_CONFIG_MAIN=1;CATCH_CONFIG_RUNTIME_STATIC_REQUIRE=1;FMT_LOCALE=1;UNICODE=1;_UNICODE=1;CMAKE_INTDIR="Debug"...
ninja: build stopped: subcommand failed.
task: Failed to run task "coverage": task: Failed to run task "build_template": exit status 1

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

Add fuzzer support for Visual Studio 2022

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

Add `package_project` function to package a project for external usage from vcpkg, conan, etc

Manually packaging/exporting a project for external users via the built-in CMake functions like install and configure_package_config_file is cumbersome. This whole thing can be abstracted away using a simple function that does it all.

Some examples of such functions:

https://github.com/TheLartians/PackageProject.cmake
https://github.com/robotology/ycm/blob/master/modules/InstallBasicPackageFiles.cmake

Related to cpp-best-practices/gui_starter_template#78

Disable linting/checks on specific target

The project as a whole is using v0.22.4 and calls dynamic_project_options with ENABLE_CONAN and CONAN_OPTIONS parameters. CMake is generating a debug build and developer mode is on.

I have a library within my project that utilizes protobuf/grpc and generates a lot of code. This library never links against project_options or project_warnings. That library is then linked to the executable that requires it using target_link_system_libraries(exe PRIVATE protoObjects). However, I still get tons of errors against that generated code. The sanitizers/linters would be great to use across the rest of the app, but not this single target. As such, I'm hoping there's an option, workaround, or otherwise to be able to prevent static analysis against this target.

Including project_options in the installed package for interface libraries

see a178b9c

bash-3.2$ cd -
/Users/clausklein/cmake/cmakelib/test_install/build
bash-3.2$ ninja
[0/1] Re-running CMake...
-- vcpkg is already installed at /Users/clausklein/vcpkg.
-- Running vcpkg install
Detecting compiler hash for triplet x64-osx...
All requested packages are currently installed.
Restored 0 packages from /Users/clausklein/.cache/vcpkg/archives in 2.44 us. Use --debug to see more details.

Total elapsed time: 1.746 s

The package eigen3 provides CMake targets:

    find_package(Eigen3 CONFIG REQUIRED)
    target_link_libraries(main PRIVATE Eigen3::Eigen)

The package fmt provides CMake targets:

    find_package(fmt CONFIG REQUIRED)
    target_link_libraries(main PRIVATE fmt::fmt)

    # Or use the header-only version
    find_package(fmt CONFIG REQUIRED)
    target_link_libraries(main PRIVATE fmt::fmt-header-only)

-- Running vcpkg install - done
CMake Error at /Users/clausklein/vcpkg/scripts/buildsystems/vcpkg.cmake:782 (_find_package):
  Found package configuration file:

    /Users/clausklein/cmake/cmakelib/install/share/myproj_header_only_lib/myproj_header_only_libConfig.cmake

  but it set myproj_header_only_lib_FOUND to FALSE so package
  "myproj_header_only_lib" is considered to be NOT FOUND.  Reason given by
  package:

  The following imported targets are referenced, but are missing:
  myproj::project_options myproj::project_warnings

Call Stack (most recent call first):
  CMakeLists.txt:45 (find_package)


-- Configuring incomplete, errors occurred!
See also "/Users/clausklein/cmake/cmakelib/test_install/build/CMakeFiles/CMakeOutput.log".
See also "/Users/clausklein/cmake/cmakelib/test_install/build/CMakeFiles/CMakeError.log".
FAILED: CMakeFiles/impl-Debug.ninja build-Debug.ninja CMakeFiles/impl-Release.ninja build-Release.ninja CMakeFiles/impl-RelWithDebInfo.ninja build-RelWithDebInfo.ninja build.ninja 
/usr/local/Cellar/cmake/3.22.1/bin/cmake --regenerate-during-build -S/Users/clausklein/cmake/cmakelib/test_install -B/Users/clausklein/cmake/cmakelib/test_install/build
ninja: error: rebuilding 'build.ninja': subcommand failed
bash-3.2$ 

Upvote & Fund

@aminya is using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

Thank you in advance for helping prioritize & fund our backlog!


Fund with Polar

the test_install does not build (include path wrong set in cmake config package)

:~/.cache/CPM/project_options/test_install$ cmake -B build -G Ninja -D CMAKE_PREFIX_PATH=$PWD/../test/stage/usr/local
-- vcpkg is already installed at ~/vcpkg.
-- Running vcpkg install
Detecting compiler hash for triplet x64-linux...
All requested packages are currently installed.
Restored 0 packages from ~/.cache/vcpkg/archives in 1 us. Use --debug to see more details.

Total elapsed time: 1.628 s

The package eigen3 provides CMake targets:

    find_package(Eigen3 CONFIG REQUIRED)
    target_link_libraries(main PRIVATE Eigen3::Eigen)

The package fmt provides CMake targets:

    find_package(fmt CONFIG REQUIRED)
    target_link_libraries(main PRIVATE fmt::fmt)

    # Or use the header-only version
    find_package(fmt CONFIG REQUIRED)
    target_link_libraries(main PRIVATE fmt::fmt-header-only)

-- Running vcpkg install - done
-- The default CMAKE_CXX_STANDARD used by external targets and tools is not set yet. Using the latest supported C++ standard that is 20
-- The default CMAKE_C_STANDARD used by external targets and tools is not set yet. Using the latest supported C standard that is 17
-- Interprocedural optimization is enabled. In other projects, linking with the compiled libraries of this project might require `set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON)`
-- /usr/bin/ccache found and enabled
-- Conan: Adding cci remote repository (https://center.conan.io) verify ssl (True)
-- Conan: Adding bincrafters remote repository (https://bincrafters.jfrog.io/artifactory/api/conan/public-conan) verify ssl (True)
-- Single configuration build!
-- Running Conan for build type 'RelWithDebInfo'
-- Conan: checking conan executable
-- Conan: Found program ~/.local/bin/conan
-- Conan: Version found Conan version 1.46.1
-- Conan executing:~/.local/bin/conan install ~/.cache/CPM/project_options/test_install --build missing --env CC=/usr/bin/cc --env CXX=/usr/bin/c++ --settings build_type=RelWithDebInfo --settings compiler=gcc --settings compiler.version=10 --settings compiler.libcxx=libstdc++11 --settings compiler.cppstd=20
Configuration:
[settings]
arch=x86_64
arch_build=x86_64
build_type=RelWithDebInfo
compiler=gcc
compiler.cppstd=20
compiler.libcxx=libstdc++11
compiler.version=10
os=Linux
os_build=Linux
[options]
[build_requires]
[env]
CC=/usr/bin/cc
CXX=/usr/bin/c++
conanfile.txt: Installing package
Requirements
    docopt.cpp/0.6.3 from 'cci' - Cache
Packages
    docopt.cpp/0.6.3:8a88cc7b41866206faedec217e3c9b3f0f909078 - Cache

Installing (downloading, building) binaries...
docopt.cpp/0.6.3: Already installed!
conanfile.txt: Generator cmake_find_package_multi created docopt-config-version.cmake
conanfile.txt: Generator cmake_find_package_multi created docoptTarget-relwithdebinfo.cmake
conanfile.txt: Generator cmake_find_package_multi created docoptTargets.cmake
conanfile.txt: Generator cmake_find_package_multi created docopt-config.cmake
conanfile.txt: Generator txt created conanbuildinfo.txt
conanfile.txt: Aggregating env generators
conanfile.txt: Generated conaninfo.txt
conanfile.txt: Generated graphinfo
-- Library docopt found ~/.conan/data/docopt.cpp/0.6.3/_/_/package/8a88cc7b41866206faedec217e3c9b3f0f909078/lib/libdocopt.a
-- Found: 
~/.conan/data/docopt.cpp/0.6.3/_/_/package/8a88cc7b41866206faedec217e3c9b3f0f909078/lib/libdocopt.a
-- Library docopt found ~/.conan/data/docopt.cpp/0.6.3/_/_/package/8a88cc7b41866206faedec217e3c9b3f0f909078/lib/libdocopt.a
-- Found: 
~/.conan/data/docopt.cpp/0.6.3/_/_/package/8a88cc7b41866206faedec217e3c9b3f0f909078/lib/libdocopt.a
-- Configuring done
-- Generating done
-- Build files have been written to: ~/.cache/CPM/project_options/test_install/build
:~/.cache/CPM/project_options/test_install$ cd build
 :~/.cache/CPM/project_options/test_install/build$ ninja
[1/2] Building CXX object CMakeFiles/another_main.dir/another_main.cpp.o
FAILED: CMakeFiles/another_main.dir/another_main.cpp.o
~/.local/lib/python3.8/site-packages/cmake/data/bin/cmake -E __run_co_compile --launcher=/usr/bin/ccache --tidy="~/.local/bin/clang-tidy;-extra-arg=-Wno-unknown-warning-option;-extra-arg=-std=c++20;--extra-arg-before=--driver-mode=g++" --cppcheck="/usr/bin/cppcheck;--template=gcc;--enable=style,performance,warning,portability;--inline-suppr;--suppress=internalAstError;--suppress=unmatchedSuppression;--inconclusive;--std=c++20" --source=~/.cache/CPM/project_options/test_install/another_main.cpp -- /usr/bin/c++ -DFMT_LOCALE -isystem ~/.cache/CPM/project_options/test/stage/usr/local/. -isystem ~/.cache/CPM/project_options/test_install/build/vcpkg_installed/x64-linux/include -isystem ~/.cache/CPM/project_options/test_install/build/vcpkg_installed/x64-linux/include/eigen3 -O2 -g -DNDEBUG -flto -fno-fat-lto-objects -fdiagnostics-color=always -Wall -Wextra -Wshadow -Wnon-virtual-dtor -Wold-style-cast -Wcast-align -Wunused -Woverloaded-virtual -Wpedantic -Wconversion -Wsign-conversion -Wnull-dereference -Wdouble-promotion -Wformat=2 -Wimplicit-fallthrough -Wmisleading-indentation -Wduplicated-cond -Wduplicated-branches -Wlogical-op -Wuseless-cast -march=native --coverage -O0 -g -std=c++2a -MD -MT CMakeFiles/another_main.dir/another_main.cpp.o -MF CMakeFiles/another_main.dir/another_main.cpp.o.d -o CMakeFiles/another_main.dir/another_main.cpp.o -c ~/.cache/CPM/project_options/test_install/another_main.cpp
~/.cache/CPM/project_options/test_install/another_main.cpp:1:10: error: 'mylib/lib.hpp' file not found [clang-diagnostic-error]
#include <mylib/lib.hpp>
         ^
1 warning and 2 errors generated.
Error while processing ~/.cache/CPM/project_options/test_install/another_main.cpp.
Suppressed 1 warnings (1 in non-user code).
Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
Found compiler error(s).
ninja: build stopped: subcommand failed.

~/.cache/CPM/project_options/test_install/build$ find $PWD/../../test/stage -name '*.hpp'
~/.cache/CPM/project_options/test_install/build/../../test/stage/usr/local/include/mylib/lib.hpp
~/.cache/CPM/project_options/test_install/build/../../test/stage/usr/local/include/mylib2/lib.hpp
~/.cache/CPM/project_options/test_install/build$

target_disable_clang_tidy(fmt) does not really help

ninja
# ...
/Users/clausklein/.cache/CPM/fmt/15c05aa781ab44fa13a906fe5737c1d14e5edee9/include/fmt/format.h:3036:51: error: all parameters should be named in a function [hicpp-named-parameter,readability-named-parameter,-warnings-as-errors]
constexpr auto operator"" _a(const char* s, size_t) -> detail::udl_arg<char> {
                                                  ^
                                                   /*unused*/
/Users/clausklein/.cache/CPM/fmt/15c05aa781ab44fa13a906fe5737c1d14e5edee9/include/fmt/format.h:3043:62: error: parameter name 's' is too short, expected at least 3 characters [readability-identifier-length,-warnings-as-errors]
FMT_DEPRECATED constexpr auto operator"" _format(const char* s, size_t n)
                                                             ^
/Users/clausklein/Workspace/cpp/ModernCmakeStarter/source/greeter.cpp:4:1: error: do not use namespace using-directives; use using-declarations instead [google-build-using-namespace,-warnings-as-errors]
using namespace greeter;
^
58184 warnings generated.
Suppressed 56453 warnings (56449 in non-user code, 4 with check filters).
Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
1018 warnings treated as errors
ninja: build stopped: subcommand failed.
Claus-iMac:build-ModernCmakeStarter-Debug clausklein$ builddriver ninja
builddriver executing: 'ninja'
Compilation FAILED in 6.547162 seconds
Number of warnings: 0
Number of errors: 1018
Last Error:
  Message: "do not use namespace using-directives; use using-declarations instead [google-build-using-namespace,-warnings-as-errors]"
  Path: /Users/clausklein/Workspace/cpp/ModernCmakeStarter/source/greeter.cpp
  Line Number: 4
  Column: 1
For full log, please open: /var/folders/wb/ckvxxgls5db7qyhqq4y5_l1c0000gq/T/build-snfb9p3a.log
Claus-iMac:build-ModernCmakeStarter-Debug clausklein$ ninja -nv
[1/4] /usr/local/Cellar/cmake/3.24.1/bin/cmake -E __run_co_compile --launcher=/usr/local/bin/ccache --tidy="/usr/local/opt/llvm/bin/clang-tidy;-extra-arg=-Wno-unknown-warning-option;-warnings-as-errors=*;-extra-arg=-std=c++20;--extra-arg-before=--driver-mode=g++" --source=/Users/clausklein/Workspace/cpp/ModernCmakeStarter/source/greeter.cpp -- /Applications/Xcode.app/Contents/Developer/usr/bin/g++ -DFMT_LOCALE -I/Users/clausklein/.cache/CPM/fmt/15c05aa781ab44fa13a906fe5737c1d14e5edee9/include -isystem /Users/clausklein/Workspace/cpp/ModernCmakeStarter/include -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -fcolor-diagnostics -std=c++20 -MD -MT _deps/greeter-build/CMakeFiles/greeter.dir/source/greeter.cpp.o -MF _deps/greeter-build/CMakeFiles/greeter.dir/source/greeter.cpp.o.d -o _deps/greeter-build/CMakeFiles/greeter.dir/source/greeter.cpp.o -c /Users/clausklein/Workspace/cpp/ModernCmakeStarter/source/greeter.cpp
[2/4] : && /usr/local/Cellar/cmake/3.24.1/bin/cmake -E rm -f _deps/greeter-build/libgreeter.a && /usr/bin/ar qc _deps/greeter-build/libgreeter.a  _deps/greeter-build/CMakeFiles/greeter.dir/source/greeter.cpp.o && /usr/bin/ranlib _deps/greeter-build/libgreeter.a && /usr/local/Cellar/cmake/3.24.1/bin/cmake -E touch _deps/greeter-build/libgreeter.a && :
[3/4] : && /Applications/Xcode.app/Contents/Developer/usr/bin/g++ -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names  standalone/CMakeFiles/GreeterStandalone.dir/source/main.cpp.o -o standalone/GreeterStandalone  _deps/greeter-build/libgreeter.a  _deps/fmt-build/libfmtd.a && :
[4/4] : && /Applications/Xcode.app/Contents/Developer/usr/bin/g++ -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names  test/CMakeFiles/GreeterTests.dir/source/main.cpp.o test/CMakeFiles/GreeterTests.dir/source/greeter.cpp.o -o test/GreeterTests  _deps/greeter-build/libgreeter.a  _deps/fmt-build/libfmtd.a && :
Claus-iMac:build-ModernCmakeStarter-Debug clausklein$ 

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

CMAKE_CXX_STANDARD 23 when compiling with gcc makes clang-tidy fail

The C++23 standard initial support was in CMake 3.20. However, there seems to be some disagreement between GCC and Clang regarding the standard compiler flags.

For instance, while GCC accepts both -std=c++23 and -std=c++2b, Clang only accepts -std=c++2b. For this reason, when trying to enable clang-tidy and C++23 while compiling with GCC, Clang fails with a message indicating that the flag -std=c++23 does not exist.

I'm not sure if it's worthy fixing this, as Clang will eventually add the correct flag. Meanwhile, it prevents the user from enabling clang-tidy while compiling using GCC and C++23.

Doxygen: automate the addition of the extensions (dark toggle, copy button) using CMake

Is it possible to automate the addition of the extensions (dark toggle, copy button) using CMake?

https://github.com/cpp-best-practices/project_options/blob/50eb09a1097c8ae90b5bc84729a33577365d5eb5/src/Doxygen.cmake

Originally posted by @aminya in #88 (comment)


Afaik to inject Javascript into Doxygen you have to provide a header template like described in the install instructions of the extensions. If there would be an easier way I'd love to know about it as well!

So I think the answer is no, there is no easy way to automate the addition of the extensions with just the CMake Doxygen module. Maybe you could ship a custom header template with your CMake module, with all the extensions installed? But personally, as a user, I'd not be a fan of that bc I need control over the header template for injecting SEO-Metadata and the "github corner".

It may be worth a try to directly ask your question in doxygen/doxygen?

Originally posted by in #88 (comment)

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

Warning is valid for C++/ObjC++ but not for C

When compiling with GCC, it complains some warnings are not for C. We may need to set different warnings for different languages.

cc1: warning: command-line option ‘-Wnon-virtual-dtor’ is valid for C++/ObjC++ but not for C
cc1: warning: command-line option ‘-Wold-style-cast’ is valid for C++/ObjC++ but not for C                                                                                            
cc1: warning: command-line option ‘-Woverloaded-virtual’ is valid for C++/ObjC++ but not for C
cc1: warning: command-line option ‘-Wuseless-cast’ is valid for C++/ObjC++ but not for C

Overriding dynamic_project_options on CMake command line does not work

Trying to run a command such as:
cmake -S . -B ./build -G "Ninja Multi-Config" -DCMAKE_BUILD_TYPE:STRING=Debug -DENABLE_DEVELOPER_MODE:BOOL=OFF -DOPT_ENABLE_COVERAGE:BOOL=ON -DOPT_ENABLE_INCLUDE_WHAT_YOU_USE:BOOL=OFF

Results in the options not being overriden.
The CMakeCache.txt contains

//Analyze and report on coverage
OPT_ENABLE_COVERAGE:INTERNAL=ON
//Enable include-what-you-use analysis during compilation
OPT_ENABLE_INCLUDE_WHAT_YOU_USE:INTERNAL=OFF

Which seems correct, but my compile_commands.json does not contain any coverage flags and digging further into this I found that when DynamicProjectOptions.cmake:130 is parsed

cmake_dependent_option(
      OPT_${option_name}
      "${option_description}"
      ${option_developer_default}
      ENABLE_DEVELOPER_MODE
      ${option_user_default})

it overrides the command line option by the developer default or user default. In ENABLE_COVERAGE case it disables coverage in both configurations no matter what I pass to the command line

So this if here

if(OPT_${option_name})
  set(${option_name}_VALUE ${option_name})
else()
  unset(${option_name}_VALUE)
endif()

always unsets the value

CMake v3.24 DOWNLOAD_EXTRACT_TIMESTAMP warning

When including project_options via FetchContent_Declare CMake displays a couple of warnings which (to my knowledge) are not disableable.
AFAIK, there are two solutions, either set policy with cmake_policy(SET CMP0135 [NEW/OLD]) or add DOWNLOAD_EXTRACT_TIMESTAMP true to FetchContent_Declare calls in Doxygen.cmake:35, PackageProject.cmake:169 and PackageProject.cmake:191

Error in macro enable_native_optimization

I got the error:

CMake Error at build/_deps/_project_options-src/src/Optimization.cmake:18 (target_compile_options):
  Cannot specify compile options for target "PRIVATE" which is not built by
  this project.

The reason is that the macro lacks a parameter to receive project_name.

Add codespell to checkers

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

Test '-march=native' support for all architectures and platforms

This flag fails on some ARM platforms including the Apple M1 (1, 2). We may be able to check whether it is supported by using clang -march=native -cx /dev/null (1, 2) before adding to the compile options.

Upvote & Fund

  • I am using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar

New CMake versions need FILE_SET installation

New CMake version fails with this error:

CMake error: install TARGETS target my_header_lib is exported but not all of its interface file sets are installed

To prevent this, I need to patch the install rule

Claus-iMac:d3e91bd4d5ecbedc9f73927e56449814005472d0 clausklein$ git diff

diff --git a/src/PackageProject.cmake b/src/PackageProject.cmake
index f272175..8210448 100644
--- a/src/PackageProject.cmake
+++ b/src/PackageProject.cmake
@@ -154,7 +154,9 @@ function(package_project)
     LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT shlib
     ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT lib
     RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" COMPONENT bin
-    PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${_PackageProject_NAME}" COMPONENT dev)
+    PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${_PackageProject_NAME}" COMPONENT dev
+    FILE_SET HEADERS # NOTE: required from CMake to install the FILE_SET HEADERS too!
+  )
 
   # download ForwardArguments
   FetchContent_Declare(

Claus-iMac:d3e91bd4d5ecbedc9f73927e56449814005472d0 clausklein$

see too https://github.com/ClausKlein/cpp_cmake_project/blob/e393e84856c2842a7a50876417fa14b4b9ea6a27/my_header_lib/CMakeLists.txt#L2

Upvote & Fund

@aminya is using Polar.sh so you can upvote and help fund this issue. The funding is received once the issue is completed & confirmed by you.

Thank you in advance for helping prioritize & fund our backlog!


Fund with Polar

v0.24.0, Visual Studio 2022 linker doesn't understand sanitizers?

#135

I think it is related with this.
After I cleaned up my out folder, build reports this kind of error

  Cleaning... 0 files.
  [1/14] Building CXX object fuzz_test\CMakeFiles\fuzz_tester.dir\fuzz_tester.cpp.obj
E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\cl : Command line warning D9002: ignoring unknown option '/fsanitize=fuzzer'
  [2/14] Linking CXX executable fuzz_test\fuzz_tester.exe
  FAILED: fuzz_test/fuzz_tester.exe 
  cmd.exe /C "cd . && "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E vs_link_exe --intdir=fuzz_test\CMakeFiles\fuzz_tester.dir --rc=C:\PROGRA~2\WI3CF2~1\10\bin\100190~1.0\x64\rc.exe --mt=C:\PROGRA~2\WI3CF2~1\10\bin\100190~1.0\x64\mt.exe --manifests  -- C:\PROGRA~2\MICROS~4\2019\PROFES~1\VC\Tools\MSVC\1429~1.301\bin\Hostx64\x64\link.exe /nologo fuzz_test\CMakeFiles\fuzz_tester.dir\fuzz_tester.cpp.obj  /out:fuzz_test\fuzz_tester.exe /implib:fuzz_test\fuzz_tester.lib /pdb:fuzz_test\fuzz_tester.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:console  /fsanitize=address /fsanitize=fuzzer -LIBPATH:C:\PROGRA~2\MICROS~4\2019\PROFES~1\VC\Tools\MSVC\1429~1.301\ATLMFC\lib\x64   -LIBPATH:C:\PROGRA~2\MICROS~4\2019\PROFES~1\VC\Tools\MSVC\1429~1.301\lib\x64   -LIBPATH:C:\PROGRA~2\MICROS~4\2019\PROFES~1\VC\Tools\MSVC\1429~1.301\lib\x86\store\REFERE~1   -LIBPATH:C:\PROGRA~2\WI3CF2~1\10\lib\100190~1.0\ucrt\x64   -LIBPATH:C:\PROGRA~2\WI3CF2~1\10\lib\100190~1.0\um\x64   -LIBPATH:"C:\Program Files (x86)\Windows Kits\10\References\x64" vcpkg_installed\x64-windows\debug\lib\fmtd.lib  kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib && cmd.exe /C "cd /D E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\fuzz_test && C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noprofile -executionpolicy Bypass -file C:/dev/vcpkg/scripts/buildsystems/msbuild/applocal.ps1 -targetBinary E:/work/Knuckles/Game/out/build/windows-msvc-debug-hard-mode/fuzz_test/fuzz_tester.exe -installedDir E:/work/Knuckles/Game/out/build/windows-msvc-debug-hard-mode/vcpkg_installed/x64-windows/debug/bin -OutVariable out""
  LINK Pass 1: command "C:\PROGRA~2\MICROS~4\2019\PROFES~1\VC\Tools\MSVC\1429~1.301\bin\Hostx64\x64\link.exe /nologo fuzz_test\CMakeFiles\fuzz_tester.dir\fuzz_tester.cpp.obj /out:fuzz_test\fuzz_tester.exe /implib:fuzz_test\fuzz_tester.lib /pdb:fuzz_test\fuzz_tester.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:console /fsanitize=address /fsanitize=fuzzer -LIBPATH:C:\PROGRA~2\MICROS~4\2019\PROFES~1\VC\Tools\MSVC\1429~1.301\ATLMFC\lib\x64 -LIBPATH:C:\PROGRA~2\MICROS~4\2019\PROFES~1\VC\Tools\MSVC\1429~1.301\lib\x64 -LIBPATH:C:\PROGRA~2\MICROS~4\2019\PROFES~1\VC\Tools\MSVC\1429~1.301\lib\x86\store\REFERE~1 -LIBPATH:C:\PROGRA~2\WI3CF2~1\10\lib\100190~1.0\ucrt\x64 -LIBPATH:C:\PROGRA~2\WI3CF2~1\10\lib\100190~1.0\um\x64 -LIBPATH:C:\Program Files (x86)\Windows Kits\10\References\x64 vcpkg_installed\x64-windows\debug\lib\fmtd.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:fuzz_test\CMakeFiles\fuzz_tester.dir/intermediate.manifest fuzz_test\CMakeFiles\fuzz_tester.dir/manifest.res" failed (exit code 1120) with the following output:
E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\LINK : warning LNK4044: unrecognized option '/fsanitize=address'; ignored
E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\LINK : warning LNK4044: unrecognized option '/fsanitize=fuzzer'; ignored
E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\LINK : warning LNK4300: ignoring '/INCREMENTAL' because input module contains ASAN metadata
E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\LINK : warning LNK4044: unrecognized option '/fsanitize=address'; ignored
E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\LINK : warning LNK4044: unrecognized option '/fsanitize=fuzzer'; ignored
     Creating library fuzz_test\fuzz_tester.lib and object fuzz_test\fuzz_tester.exp
E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\LIBCMTD.lib(exe_main.obj) : error LNK2019: unresolved external symbol main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
E:\work\Knuckles\Game\out\build\windows-msvc-debug-hard-mode\fuzz_test\fuzz_tester.exe : fatal error LNK1120: 1 unresolved externals
  [3/14] Building CXX object knuckles\test\constexpr\CMakeFiles\my_lib_relaxed_constexpr_tests.dir\constexpr_tests.cpp.obj
  [4/14] Building CXX object knuckles\test\CMakeFiles\my_lib_tests.dir\tests.cpp.obj
  [5/14] Building CXX object console_app\test\CMakeFiles\my_exe_helpers_tests.dir\tests.cpp.obj
  [6/14] Building CXX object knuckles\test\constexpr\CMakeFiles\my_lib_constexpr_tests.dir\constexpr_tests.cpp.obj
  [7/14] Building CXX object console_app\CMakeFiles\knuckles_exe.dir\src\main.cpp.obj
  [8/14] Building CXX object knuckles\CMakeFiles\knuckles_lib.dir\src\lib.cpp.obj

I don't know what is my environment has wrong though...
it's all good if I downgrade 0.21.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.