How do I use find_package in CMakeLists.txt such that if an optional dependency is not installed, I still get a makefile? - cmake

My goal is to create a CMakeLists.txt file that builds a suite of programs for the local system. If the conditions for building some programs are not satisfied, I wish to be able to build the rest of the programs. The sticking point seems to be gtk, but bear in mind that I don't think a gtk-specific method is the best choice.
For many modules you'd want to build with, you can use
find_package(PkgConfig REQUIRED)
To set up the pkg-config wrapper pkg_check_Modules and if you don't use REQUIRED you can check the _FOUND variable:
pkg_check_Modules(FT REQUIRED freetype2)
if (FT_FOUND)
message(STATIC "Found freetype2")
#Continue and succeed, using FreeType library
else()
message(STATIC "Didn't find freetype2")
#Continue and succeed, without using FreeType library
endif()
Other libraries don't seem to work with pkg_check_modules so I have resorted to find_package
find_package(GTK2 2.0 QUIET gtk)
if (GTK2_FOUND)
...
endif()
Here's a complete reduction:
cmake_minimum_required(VERSION 3.6.2)
project (test C CXX)
set (SOURCE a.cpp b.cpp)
find_package(AMAZING 2.0 QUIET amazing_testing)
if (AMAZING_FOUND)
list(APPEND SOURCE c.cpp)
else()
list(APPEND SOURCE d.cpp)
endif()
add_executable(test ${SOURCE})
The above allows my whole CMakeLists.txt to proceed to the end, but I get an error, no makefile is created, and build/CMakeFiles/CMakeOutput.log doesn't even mention gtk:
CMake Error at gtk/CMakeLists.txt:4 (find_package):
find_package called with invalid argument "amazing_testing"
## here would be further cmake processing logs from other necessary setup
-- Configuring incomplete, errors occurred!
See also "/home/menright/bit/build/CMakeFiles/CMakeOutput.log".
How can I tweak such a usage of find_package so that if the optional package does not exist, the configure will complete successfully anyway? Alternatively, what should I use instead of find_package that will concisely set up usage of a library the way pkg_check_modules does and yet allow success if the library is not available?

Related

Why is the toolchain file executed a few times in CMake?

In an attempt to create a cross-compilation CMake toolchain template with the SDCC compiler, I have come across a very weird issue.
As described in this link, if the toolchain.cmake file defines a CMAKE_SYSTEM_NAME, CMake will look for the file with the ${CMAKE_SYSTEM_NAME}.cmake under the Module/Platform directory. And this file should define platform-specific options. In my case, I am using it to find the sdcc compiler and setting some compiler flags.
This works just fine for me. Using cmake -DCMAKE_MODULE_PATH="${PATH_TO_MY_MODULES}" -DCMAKE_TOOLCHAIN_FILE="${PATH_TO_MY_TOOLCHAIN}" -DSDCC_SYSROOT="SOME_VALUE", CMake finds all the correct toolchain and platform files.
It seems like the toolchain and the platform file are executed (not sure if that's the correct term) a few times during the configuration process. In the first few times, the variable SDCC_SYSROOT I passed in the CMake command has the value SOME_VALUE as expected. However, the same variable SDCC_SYSROOT seems to lose the value in the last time these toolchain/platform files are executed. So they are empty. This causes my script to generate a fatal error.
toolchain.cmake has the following contents:
set(CMAKE_SYSTEM_NAME SDCC_PIC_16F877A)
# Finding resource settings
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
# Set default MCU family and model
if (NOT MICROCHIP_FAMILY)
set(MICROCHIP_FAMILY "pic16")
endif()
if (MICROCHIP_MODEL STREQUAL "pic16")
set(MICROCHIP_MODEL "16f877a")
endif()
# Need a better way to detect the supported models here
if (NOT MICROCHIP_FAMILY STREQUAL "pic16" AND NOT MICROCHIP_MODEL STREQUAL "16f877a")
message(FATAL_ERROR "Settings not supported. Please drop a request.")
endif()
if (NOT SDCC_ROOT)
message(FATA_ERROR "Need to provide the root (from toolchain.)")
endif()
# Cache those variables
set(SDCC_ROOT "${SDCC_ROOT}"
CACHE INTERNAL "Root directory of SDCC installation")
set(MICROCHIP_FAMILY "${MICROCHIP_FAMILY}"
CACHE INTERNAL "Family of the chip to compile for")
set(MICROCHIP_MODEL "${MICROCHIP_MODEL}"
CACHE INTERNAL "Model of the chip to compile for")
the Module/Platform/SDCC_PIC_16F877A.cmake file has the contents:
# Check if the shit exists
message("!!! The value of root is ${SDCC_ROOT}")
if (NOT SDCC_ROOT)
message(FATAL_ERROR
"SDCC_ROOT is not defined. Please set this variable e.g.\n"
"cmake -DSDCC_ROOT=\"C:/Program Files/sdcc\"")
endif()
# Finding the compilers
find_program(CMAKE_C_COMPILER
sdcc
PATHS ${SDCC_ROOT}
PATH_SUFFIXES "bin"
DOC "path to the SDCC C compiler.")
and my CMakeLists.txt is the following:
cmake_minimum_required(VERSION 3.10)
project(PicExample)
message("THE COMPILER IS ${CMAKE_C_COMPILER}")
add_executable(pic_example main.c)
what I invoke from my project/build directory and the error I get:
cmake -DCMAKE_MODULE_PATH:FILEPATH="/mnt/c/Users/mathe/Desktop/coding/sdcc-pic-template/Modules" -DCMAKE_TOOLCHAIN_FILE:FILEPATH="/mnt/c/Users/mathe/Desktop/coding/sdcc-pic-template/Modules/toolchain.cmake" -DSDCC_ROOT="testing/" ..
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
!!! The value of root is testing/
!!! The value of root is testing/
-- Check for working C compiler: /usr/bin/cc
FATA_ERRORNeed to provide the root (from toolchain.)
!!! The value of root is
CMake Error at /mnt/c/Users/mathe/Desktop/coding/sdcc-pic-template/Modules/Platform/SDCC_PIC_16F877A.cmake:4 (message):
SDCC_ROOT is not defined. Please set this variable e.g.
cmake -DSDCC_ROOT="C:/Program Files/sdcc"
Call Stack (most recent call first):
/usr/share/cmake-3.16/Modules/CMakeSystemSpecificInformation.cmake:26 (include)
/mnt/c/Users/mathe/Desktop/coding/sdcc-pic-template/build/CMakeFiles/CMakeTmp/CMakeLists.txt:3 (project)
CMake Error at /usr/share/cmake-3.16/Modules/CMakeTestCCompiler.cmake:44 (try_compile):
Failed to configure test project build system.
Call Stack (most recent call first):
CMakeLists.txt:2 (project)
-- Configuring incomplete, errors occurred!
See also "/mnt/c/Users/mathe/Desktop/coding/sdcc-pic-template/build/CMakeFiles/CMakeOutput.log".
Why do the toolchain files get "executed" more than once by CMake and has no access to cache in the latest runs? I've been finding CMake documentation for cross-compilation very difficult, especially if you are working with a non-standard compiler.
I am aware that other people have had same issues before, but I am not simply asking for a simple hacky solution (setting environment variables). I actually want to know why this happens (which the previous answers don't tackle).
Tsyvarev answered the why the toolchain is used multiple times in CMake. TLDR; CMake needs it for multiple try_compile() calls it uses internally for error checking and other things.
This works just fine for me.
-DCMAKE_MODULE_PATH="${PATH_TO_MY_MODULES}" -DCMAKE_TOOLCHAIN_FILE="${PATH_TO_MY_TOOLCHAIN}" -DSDCC_SYSROOT="SOME_VALUE",
To fix your problem here is what you need to do.
Essentially you are passing an argument to your toolchain file. And this argument SDCC_SYSROOT essentially goes out of scope.
To fix this problem here is what you need to do.
# Use list(APPEND) rather than set() so that any variables added by CMake aren't lost!
#
# Here is the docs for this variable:
# https://cmake.org/cmake/help/latest/variable/CMAKE_TRY_COMPILE_PLATFORM_VARIABLES.html
list(APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES ${SDCC_SYSROOT})
If you want to see how many times your toolchain script gets executed try putting in a message() call in there for fun.
And if you are really interested look inside your build folder and see what it is CMake is doing.
If you are wondering how I know this information it's because I read the toolchain section in Craig Scott's CMake book "Professional CMake:
A Practical Guide"
Here is a link: https://crascit.com/professional-cmake/
For determine, whether some feature is supported by the compiler or by some library, CMake uses try_compile approach: during the configuration phase, it creates separate CMake project and immediately configures and builds it. Because it is a separate project, its configuration has the same steps as the main project and it loads the toolchain file too.
try_compile could be used by the (user) project for check features of the library or of the compiler. There are many CMake modules which use try_compile in their implementation. E.g. CheckSymbolExists.
try_compile is also used by CMake itself, in platform files, when it perform basics checks for the compiler. In your log you could find the line:
CMake Error at /usr/share/cmake-3.16/Modules/CMakeTestCCompiler.cmake:44 (try_compile)
Aside from try_compile, the new CMake project is created in ExternalProject_Add command. That creation is also accompanied by the reading of the toolchain file. (More correctly, the new project is created not when ExternalProject_Add invocation is processed but when corresponding project is configured. This configuration is performed on the build stage of the main project.)

Can't seem to include Glut to my cmake project Ubuntu [duplicate]

I've been stuck for a while now and I can't figure out how to get freeglut working. I thought I knew what it was asking me to do, so I added that set(prefix_path) line but it didn't do anything. Am I supposed to write my own freeglut-config.cmake or what?
Note: I am using the freeglut for MinGW package from this website
CMake File:
cmake_minimum_required(VERSION 3.7)
project(HW1)
set(CMAKE_CXX_STANDARD 11)
set(SOURCE_FILES Triangle.cpp)
set(CMAKE_PREFIX_PATH "C:/freeglut")
find_package(GLEW REQUIRED STATIC)
find_package(FREEGLUT REQUIRED)
find_package(OPENGL REQUIRED)
include_directories(${FREEGLUT_INCLUDE_DIRS} ${GLEW_INCLUDE_DIRS} ${OPENGL_INCLUDE_DIRS})
link_directories(${FREEGLUT_LIBRARY_DIRS} ${GLEW_LIBRARY_DIRS} ${OPENGL_LIBRARY_DIRS})
add_definitions(${FREEGLUT_DEFINITIONS} ${GLEW_DEFINITIONS} ${OPENGL_DEFINITIONS})
add_executable(HW1 ${SOURCE_FILES})
target_link_libraries(HW1 ${FREEGLUT_LIBRARIES} ${GLEW_LIBRARIES} ${OPENGL_LIBRARIES})
Full error:
CMake Error at CMakeLists.txt:8 (find_package):
By not providing "FindFREEGLUT.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "FREEGLUT",
but CMake did not find one.
Could not find a package configuration file provided by "FREEGLUT" with any
of the following names:
FREEGLUTConfig.cmake
freeglut-config.cmake
Add the installation prefix of "FREEGLUT" to CMAKE_PREFIX_PATH or set
"FREEGLUT_DIR" to a directory containing one of the above files. If
"FREEGLUT" provides a separate development package or SDK, be sure it has
been installed.
If your application is GLUT-compatible, that it doesn't use any extension of freeglut, then it is better to search GLUT instead of FREEGLUT:
find_package(GLUT REQUIRED)
"Find" script used by this command is already shipped into CMake distro, and it searches freeglut too.
(Note, that with that command variables for include directories and linking libraries are GLUT_INCLUDE_DIR and GLUT_LIBRARY correspondingly).
If your application requires exactly freeglut (that is, uses some of its extensions incompatible with other GLUT implementations), you need to ship your package with FindFREEGLUT.cmake script and adjust CMAKE_MODULE_PATH variable correspondingly:
# Assuming you have <source-dir>/cmake/FindFREEGLUT.cmake
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
find_package(FREEGLUT REQUIRED)
You may find existing script in the net, or write it by yourself, like here.
In any case, if you have freeglut installed into non-system location, you need to hint CMake about that. E.g., by adjusting CMAKE_PREFIX_PATH.

Make FetchContent compatible with find_package

I try to add all dependencies needed for my project to compile over CMake. This should reduce the overhead others will have when they want to compile the project for the first time.
To achive this, I tried to use FetchContent. So far so good, when I link the generated targets its not a problem at all. But now I have a library depending itself on annother lib which isn't included as submodule. The lib tries to find the dependency over find_package. How can I get find_package to find the library?
What I tried so far:
adding an alias target and defined all variables set by find_package
Setting the LIB_DIR to the build directory and called find_package
Here a minimal snipped of my CMake code of the later:
cmake_minimum_required(VERSION 3.14)
find_package(ZLIB)
if (NOT ZLIB_FOUND)
FetchContent_Declare(zlib_fetch
GIT_REPOSITORY https://github.com/madler/zlib.git
GIT_TAG cacf7f1d4e3d44d871b605da3b647f07d718623f
)
FetchContent_MakeAvailable(zlib_fetch)
set(ZLIB_DIR ${zlib_fetch_BINARY_DIR})
message(${zlib_fetch_BINARY_DIR})
#simulates the call in the other library:
find_package(ZLIB REQUIRED)
endif (NOT ZLIB_FOUND)
Starting with CMake 3.24, FetchContent_Declare has OVERRIDE_FIND_PACKAGE option which, when specified, makes CMake redirect the subsequent calls to find_package(<name>) so that FetchContent_Declare(<name> ...) satisfies the dependency (note that <name> must stay the same here).

Linking GLEW with CMake

How can you link GLEW to a project with CMake?
We've been trying to link GLEW to our project using CMake for at least 3 hours without any success so any help is accepted.
I'm using the FindGLEW.cmake which comes with CMake 3.1.0
CMakeLists.txt
find_package(GLEW REQUIRED)
if (GLEW_FOUND)
include_directories($(GLEW_INCLUDE_DIRS))
endif()
Environment Variables
I'm using MinGW w64 to compile the sources and we successfully linked GLFW and GLM just by copying the includes and libs to their respective folders, but after doing the same with GLEW, CMake still couldn't find it.
Sorry if I wasn't clear enough while formulating the question. I will provide any additional information required.
Edit: I've managed to link the header files by specifying their location in the CMake Cache file, though I'm getting undefined reference to glew functions like glewInit().
Typical CMake scripts like FindGLEW will define variables that specify the paths and files that your project needs. If the script can't automatically identify the correct paths (usually because of nonstandard install location, which is fine), then it leaves these variables up to you to fill in.
With command line CMake, you use the -D flag to define and set the value of a given variable. Other CMake interfaces, like CMake-gui or an IDE integration, give you this ability some other way.
However you do it, you can also modify the cache directly (CMakeCache.txt) and see what CMake is using in there or just clear the cache altogether. You'll have to rerun CMake for it to pick up your changes.
When it comes to linking, that's when you need to tell CMake which libs to link. Use the link_libraries command with what the automated script gives you.
find_package(GLEW REQUIRED)
include_directories(${GLEW_INCLUDE_DIRS})
link_libraries(${GLEW_LIBRARIES})
Other answers do obviously work, but the target based style of cmake makes it even easier since the GLEW find module defines the imported target GLEW::GLEW. All you need is:
find_package(GLEW REQUIRED)
target_link_libraries(YourTarget GLEW::GLEW)
YourTarget is the target that you created with add_executable or add_library. No need to explicitly add include directories, they are added automatically by linking the targets.
The secret of find_package(GLEW) is in FindGLEW.cmake file with cmake install.
find_path(GLEW_INCLUDE_DIR GL/glew.h)
find_library(GLEW_LIBRARY NAMES GLEW glew32 glew glew32s PATH_SUFFIXES lib64)
The find_path and find_library commands find paths in standard system paths. If you want them to find paths in user defined directories, you should tell them.
For example:
set(CMAKE_PREFIX_PATH "d:/libs/glew-1.10.0")
set(CMAKE_LIBRARY_PATH "d:/libs/glew-1.10.0/lib/Release/Win32/")
find_package(GLEW REQUIRED)
Reference:
http://www.cmake.org/cmake/help/v3.0/command/find_path.html
http://www.cmake.org/cmake/help/v3.0/command/find_library.html
I was struggling hard to link glew to cmake through command line on mac. This might be helpful but I am not sure :) I will walk you through step by step of what I have done.
I installed Cmake source from the web.
Then I went inside the cmake folder in terminal and typed
./bootstrap && make && make install
(this will install cmake command line tools on our OS platform)
I have some exercise files. I want cmake to generate xcode files for me for all those exercise files (ex. triangles.cpp, shader.cpp etc) So i made a directory inside exercise files folder.
$ mkdir xcode
$ cd xcode
$ cmake -G "Xcode" ..
At this point, Cmake suppose to install all xcode files that included correct libraries. But there was an error :
$ cmake -G "Xcode" ..
CMake Warning (dev) at CMakeLists.txt:3 (cmake_minimum_required):
Compatibility with CMake < 2.4 is not supported by CMake >= 3.0.
This warning is for project developers. Use -Wno-dev to suppress it.
system name is: Darwin-14.1.0
system processor is: x86_64
-- Could NOT find GLEW (missing: GLEW_INCLUDE_DIR GLEW_LIBRARY)
-- Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
-- Using Cocoa for window creation
-- Using NSGL for context creation
-- Building GLFW only for the native architecture
CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
GLEW_LIBRARY
linked by target "TextureLoader" in directory /Users/Mydir/Desktop/Exercise/Exercise Files
-- Configuring incomplete, errors occurred!
Then to make sure I have installed GLEW and all its libraries correctly, I ran
$brew install glew
Yes, I have installed glew already but it was NOT linked. See the Warning below:
Warning: glew-1.12.0 already installed, it's just not linked
Then I ran the following commands:
$ brew unlink glew
$ brew link glew
And I have solved the error. So just make sure that you have linked glew. Hope this helps.
Happy Coding :)
Finally I found a simple and short CMakeLists which works if you have installed everything in default paths.(openGL, glfw and glew)
cmake_minimum_required(VERSION 3.3)
project(openGL_tutorial)
find_package(OpenGL REQUIRED)
if(NOT OPENGL_FOUND)
message("ERROR: OpenGL not found")
endif(NOT OPENGL_FOUND)
set(GL_LIBRARY GL GLU X11)
add_executable(openGL_tutorial main.cpp)
target_link_libraries(openGL_tutorial glfw GLEW libGLEW.so libGLU.so libGL.so)
For what it is worth, in 2023, this works for me, on macOS, with GLEW, GLFW, and CMake installed using Homebrew:
cmake_minimum_required(VERSION 3.10)
project(Project)
add_executable(Project main.cpp)
find_package(glfw3 REQUIRED)
find_package(GLEW REQUIRED)
target_link_libraries(Project glfw GLEW::glew)

CMake adding libraries for Windows/Linux

Visual Studio C++ 2008 / GCC 4.4.2
I have written a program to run on Linux and now I have to port my code to run on Windows. I have decided to use CMake as I want to keep the same build system for both platforms.
However, I need to link with some libraries for both platforms. In my CMakeLists.txt I have the following:
# Compile with gcc c89 standard
IF(CMAKE_COMPILER_IS_GNUCXX)
MESSAGE(STATUS "GCC detected - Adding compiler flags")
SET(CMAKE_C_FLAGS "-pthread -ggdb -Wextra -Wall -pedantic -std=c89")
ENDIF(CMAKE_COMPILER_IS_GNUCXX)
IF(WIN32)
SET(CMAKE_C_FLAGS "ws2_32.lib")
ENDIF(WIN32)
However, when I compile on Visual Studio I get the following error:
fatal error C1083: Cannot open source file: 'ws2_32.lib': No such file or directory
What can I do to resolve this problem?
========= Edit
In the top level directory
# Project Client Server
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
# Name of project
PROJECT(CLIENT_SERVER)
# Compile with gcc c89 standard
IF(CMAKE_COMPILER_IS_GNUCXX)
MESSAGE(STATUS "GCC detected - Adding compiler flags")
SET(CMAKE_C_FLAGS "-pthread -ggdb -Wextra -Wall -pedantic -std=c89")
ENDIF(CMAKE_COMPILER_IS_GNUCXX)
IF(WIN32)
SET(CMAKE_C_FLAGS "ws2_32")
ENDIF(WIN32)
# Includes
INCLUDE_DIRECTORIES(${CLIENT_SERVER_SOURCE_DIR}/cltsvr_ults)
INCLUDE_DIRECTORIES(${CLIENT_SERVER_SOURCE_DIR}/server)
INCLUDE_DIRECTORIES(${CLIENT_SERVER_SOURCE_DIR}/client)
# libraries
LINK_DIRECTORIES($CLIENT_SERVER/cltsvr_ults)
# Add subdirectories
ADD_SUBDIRECTORY(client)
ADD_SUBDIRECTORY(server)
ADD_SUBDIRECTORY(cltsvr_ults)
ADD_SUBDIRECTORY(test_client)
ADD_SUBDIRECTORY(test_server)
In the subdirectory of client I have this CMakeLists.txt
# libray called client from client.c
ADD_LIBRARY(client client)
And in the subdirectory of test_clt where I create and link my executable.
# Test client add executable
INCLUDE_DIRECTORIES($CLIENT_SERVER_SOURCE_DIR/client)
INCLUDE_DIRECTORIES($CLIENT_SERVER_SOURCE_DIR/cltsvr_ults)
# Link the library
LINK_DIRECTORIES($CLIENT_SERVER/client)
# Add the executable
ADD_EXECUTABLE(clt test_clt)
# Link the executable to the client library
IF(WIN32)
TARGET_LINK_LIBRARIES(clt client ws2_32)
ENDIF(WIN32)
Disclaimer: My answer is of philosophical nature which should encourage you to avoid touching CMAKE_C_FLAGS directly. For the direct answer that just solves your problem look what Bill ( the lead architect of the CMake btw. ) wrote.
The thing about CMake is, that it lets you describe what you want to do without referring to a specific compiler or platform. What CMake does is building the compiler and linker flags from your usage of
include_directories
add_definitions
add_library
add_executable
target_link_libraries
If there are no external dependencies, other than the compiler itself, this is all you need. For external dependencies use
find_package
It defines a set of variables, like
find_package(SDL)
defines
SDL_INCLUDE_DIR
SDL_LIBRARY
for usage with respectively include_directories and target_link_libraries. CMake ships with a bunch of so called module files, like FindSDL.cmake and many others can be googled.
The next lower level is to use
find_path
find_library
which are used in the Find???.cmake modules itself.
The CMAKE_C_FLAGS variable is composed by CMake from these commands. Modifying it means you bypass CMake. There are cases, like for special optimization flags, you want to do this, but at this point all power and thus responsibility transfered from CMake to you.
By adding ws2_32.lib to the C_FLAGS, you are using it at compile time, and not link time. If you look at the error message, you can see it it treating the file as if it were a c++ source file: Cannot open source file: 'ws2_32.lib'. target_link_libraries(target ws2_32) should work.
You need to use the Target Link Libraries command. The target would be the executable you're building.
EDIT: You shouldn't specify the libs you're linking against in C_FLAGS. You can do something like TARGET_LINK_LIBRARIES(execName, ws_32, ...). I'm not 100% sure if you need the .lib. Been a while since I used CMake.