I want to compile an example code from this site (at the bottom). I downloaded GLFW 3.0.4 source code and I built it in a custom location. I used a default settings and GLFW was built as a static library. My CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 2.8)
project(glfw_test_project)
SET(CMAKE_CXX_FLAGS "-Wall -Werror -g -std=c++11")
find_package(OpenGL REQUIRED)
include_directories(/home/user/MyLibs/OpenGL/glfw-3.0.4/include)
link_directories(/home/user/MyLibs/OpenGL/glfw-3.0.4/build/src)
add_executable(glfw_test main.cpp)
target_link_libraries(glfw_test ${OPENGL_gl_LIBRARY})
target_link_libraries(glfw_test glfw3)
When I run make I get following info:
Linking CXX executable glfw_test
/usr/bin/ld: /home/user/MyLibs/OpenGL/glfw-3.0.4/build/src/libglfw3.a(x11_clipboard.c.o): undefined reference to symbol 'XConvertSelection'
//usr/lib/x86_64-linux-gnu/libX11.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
make[2]: *** [glfw_test] Error 1
make[1]: *** [CMakeFiles/glfw_test.dir/all] Error 2
make: *** [all] Error 2
What is wrong ?
Edit1
When I build GLFW as a dynamic library everything works fine. Then the last line in my CMakeLists.txt have to be replaced with:
target_link_libraries(glfw_test glfw)
What is wrong when using a static library ?
I experienced the same problems on Ubuntu 14.04 LTS.
First: error adding symbols: DSO missing from command line shows a wrong order of linker command line parameters. This post made me realise that. You need to call $ make VERBOSE=1 to see the linker call and check it with your own eyes. Remember: TARGET_LINK_LIBRARIES() should be the last command in your CMakeLists.txt And have a look at this order explanation.
Second: if you build against static GLFW3 libraries all the X11 libraries are not automatically added to your linker call, as atsui already showed above. In the GLFW-Documentation you can find a cmake variable which should fit your needs: ${GLFW_STATIC_LIBRARIES}. To make use of it and enable a more automatic build process, let pkg-config find all dependencies for X11 libs:
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(myProject)
FIND_PACKAGE( PkgConfig REQUIRED )
pkg_search_module( GLFW3 REQUIRED glfw3 ) # sets GLFW3 as prefix for glfw vars
# now ${GLFW3_INCLUDE_DIR}, ${GLFW3_LIBRARIES} and ${GLFW3_STATIC_LIBRARIES}
# are set
INCLUDE_DIRECTORIES( ${GLFW3_INCLUDE_DIR} )
ADD_EXECUTABLE( myProject mySource.cpp )
TARGET_LINK_LIBRARIES( myProject ${GLFW_STATIC_LIBRARIES} )
# they include X11 libs
Now check the linker lib parameters again with $ make VERBOSE=1 and you should find many more X11 libs like:
-lXrandr -lXi -lXrender -ldrm -lXdamage -lXxf86vm -lXext -lX11 and -lpthread.
Third: when linking against the shared library, the dependencies to X11 etc. are resolved dynamically. That is why you don't need to explicitly add X11 lib flags to the linker. In that case you only need:
TARGET_LINK_LIBRARIES( myProject ${GLFW_LIBRARIES} )
Fourth: it happened to me, that some glfwCommands had undefined reference to - linker errors. I found out, that I installed GLFW3 in /usr/local/lib but the linker was given only the LD_LIBRARY_PATH environment variable which was only set to /usr/lib32. Adding the parameter -L/usr/local/lib solved the reference problem. To avoid it in future I've set LD_LIBRARY_PATH=/usr/lib32;/usr/local/lib;.
Hint: to check what values are in your GLFW cmake variables, print them during build:
FOREACH(item ${GLFW3_STATIC_LIBRARIES})
MESSAGE(STATUS " using lib: " ${item})
ENDFOREACH()
It seems that you resolved your own issue by rebuilding GLFW as a shared library and linking the example code with that. Instead, I'll try to answer your followup question about why it doesn't work when you try to link the static library.
Basically, if you want to link against the static library libglfw3.a, you need to link all of the dependent X11 libraries. You get an error linking the static library because you didn't specify any additional libraries to link, and CMake doesn't know what these dependencies are. You don't get an error when you link the shared library libglfw.so because the X11 libraries are linked to the shared library, and CMake knows to pull those in for you automatically.
If you want to use the static library, you can determine the necessary libraries to link as follows. According to the .pc file in GLFW, you can type this in the command-line to find out what these are:
pkg-config --static --libs x11 xrandr xi xxf86vm gl
If you translate this into a CMake command, it would look like this:
target_link_libraries( glfw_test glfw3 Xrandr Xrender Xi GL m dl drm Xdamage X11-xcb xcb-glx xcb-dri2 xcb-dri3 xcb-present xcb-sync xshmfence Xxf86vm Xfixes Xext X11 pthread xcb Xau Xdmcp)
So if you add this to the CMakeLists.txt, the example code should build without an issue.
By the way, you can automatically find the X11 libraries using CMake in the following way:
find_package(X11 REQUIRED)
target_link_libraries( my_program ${X11_LIBRARIES} )
However, the set of libraries stored in the X11_LIBRARIES variable will only contain a subset of the libraries needed for statically linking GLFW.
I'm not really sure how to properly handle static/dynamic linking in CMake, but I hope this helps.
Related
I'm trying to use wxWidgets on an arm64 macOS with vcpkg, CMake, and VS Code. Everything is wired up correctly because other vcpkg libraries include, link, and run fine. But, when I try to use wxWidgets there's a linking error.
My CMakeLists.txt:
cmake_minimum_required(VERSION 3.22.0)
project(main VERSION 0.1.0)
add_executable(main main.cpp)
set_property(TARGET main PROPERTY CXX_STANDARD 17)
find_package(wxWidgets REQUIRED)
include(${wxWidgets_USE_FILE})
target_include_directories(main PRIVATE ${wxWidgets_INCLUDE_DIRS})
target_link_libraries(main PRIVATE ${wxWidgets_LIBRARIES})
The CMake error I get:
[build] [ 50%] Linking CXX executable main
[build] ld: library not found for -llibjpeg.a>
[build] clang: error: linker command failed with exit code 1 (use -v to see invocation)
The value of the wxWidgets_LIBRARIES list (set by find_package(wxWidgets REQUIRED)):
-L/Users/myname/cpp/vcpkg/packages/wxwidgets_arm64-osx/lib;-pthread;/Users/myname/cpp/vcpkg/packages/wxwidgets_arm64-osx/lib/libwx_osx_cocoau_xrc-3.1.a;/Users/myname/cpp/vcpkg/packages/wxwidgets_arm64-osx/lib/libwx_osx_cocoau_qa-3.1.a;/Users/myname/cpp/vcpkg/packages/wxwidgets_arm64-osx/lib/libwx_baseu_net-3.1.a;/Users/myname/cpp/vcpkg/packages/wxwidgets_arm64-osx/lib/libwx_osx_cocoau_html-3.1.a;/Users/myname/cpp/vcpkg/packages/wxwidgets_arm64-osx/lib/libwx_osx_cocoau_core-3.1.a;/Users/myname/cpp/vcpkg/packages/wxwidgets_arm64-osx/lib/libwx_baseu_xml-3.1.a;/Users/myname/cpp/vcpkg/packages/wxwidgets_arm64-osx/lib/libwx_baseu-3.1.a;-lwx_osx_cocoau_core-3.1;libjpeg.a>;libjpeg.a>;libpng.a>;libpng16d.a>;libz.a>;libz.a>;libtiff.a>;libtiffd.a>;liblzma.a>;liblzma.a>;libjpeg.a>;libjpeg.a>;libz.a>;libz.a>;m;-framework AudioToolbox;-framework WebKit;-lwx_baseu-3.1;libexpat.a>;libexpat.a>;libz.a>;libz.a>;-lwxregexu-3.1;libiconv.tbd;-framework CoreFoundation;-framework Security;-framework Carbon;-framework Cocoa;-framework IOKit;-framework QuartzCore;TIFF::TIFF;expat::expat;ZLIB::ZLIB;png_static
I don't have much experience with CMake, so I don't know what the right angle bracket is for, but is that the problem? Could its being the first non-full-path file in the list mean that it doesn't know where to look?
-L is for directories, and -l is for individual library files. I see you have mixed .a files with directories. You'll need to fix that.
Your best bet is to debug cmake configure with --trace-expand and see who is setting wxWidgets_LIBRARIES to a incomplete and very strange generator expression libjpeg.a>;libjpeg.a>;libpng.a>;libpng16d.a>;
Another suspicious thing is that your library paths contain packages/wxwidgets_arm64-osx which indicates either wrong usage of vcpkg or there is a -config.cmake involved which was not fixed by vcpkg. (everything vcpkg finds via cmake should be living in /installed/<triplet>)
I installed SFML and modified the cmakeList to be able to run an SFML project. I used Msys2 to install mingw and sfml 64bit version. My cmake looks like this:
cmake_minimum_required(VERSION 3.17)
project(PHONEBOOK)
set(CMAKE_CXX_STANDARD 11)
find_package(SFML 2.5 COMPONENTS system window graphics)
add_executable(PHONEBOOK main.cpp contact.cpp contact.h phonebook.cpp phonebook.h)
target_link_directories(PHONEBOOK sfml-system sfml-window sfml-graphics)
When I run the project I get this error:
CMake Error at CMakeLists.txt:8 (target_link_directories):
target_link_directories called with invalid arguments
mingw32-make: *** [Makefile:255: cmake_check_build_system] Error 1
You need to call target_link_libraries instead of target_link_directories. As you don't have multiple installations of the sfml library, there is no need to call target_link_directories
target_link_directories is for setting the search library path.
Specifies the paths in which the linker should search for libraries
when linking a given target. Each item can be an absolute or relative
path, with the latter being interpreted as relative to the current
source directory. These items will be added to the link command.
It's because you're missing one of the mandatory keywords: <INTERFACE|PUBLIC|PRIVATE>.
Eg: target_link_directories(PHONEBOOK PRIVATE sfml-system sfml-window sfml-graphics)
I am developing a C++ library, including OpenCV, which will be used in a cross-platform Xamarin solution through a wrapper and the NuGet packaging system (see this guide). I configured a CMakeLists.txt file but I simply cannot get OpenCV to be correctly linked for both static (iOS) and dynamic (Android) libraries.
I tried to change the OpenCV_DIR variable, install and build OpenCV from sources and manually include the content of the OpenCV_INCLUDE_DIRS variable but nothing worked. I also noticed that the linking works when only using cv::Point. But the linking does not work when using cv::Mat, which I do not understand the reason.
The following is the CMakeLists.txt that I am using :
cmake_minimum_required (VERSION 3.2)
project (MyLib C CXX)
enable_testing()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
MESSAGE(STATUS "CMAKE_CXX_FLAGS: " ${CMAKE_CXX_FLAGS})
# Source and headers files
set(SOURCES File1.cpp File2.cpp)
set(HEADERS File1.h File2.h)
# Library
if(BUILD_SHARED_LIBS)
add_library (MyLib SHARED ${SOURCES} ${HEADERS})
target_compile_definitions(MyLib PUBLIC IS_BUILDING_SHARED)
else()
add_library (MyLib STATIC ${SOURCES} ${HEADERS})
endif()
# Dependencies
set(OpenCV_DIR /usr/local/Cellar/opencv/4.5.0_1/lib/cmake/opencv4)
find_package(OpenCV REQUIRED)
message(STATUS "OpenCV_INCLUDE_DIRS = ${OpenCV_INCLUDE_DIRS}")
message(STATUS "OpenCV_LIBS = ${OpenCV_LIBS}")
message(STATUS "OpenCV_DIR = ${OpenCV_DIR}")
include_directories(${OpenCV_INCLUDE_DIRS})
target_link_libraries(MyLib ${OpenCV_LIBS})
The following shows the location of OpenCV's files that are used during the build process. Everything seems alright.
-- OpenCV_INCLUDE_DIRS = /usr/local/Cellar/opencv/4.5.0_1/include/opencv4
-- OpenCV_LIBS = opencv_calib3d;opencv_core;opencv_dnn;opencv_features2d;opencv_flann;opencv_gapi;opencv_highgui;opencv_imgcodecs;opencv_imgproc;opencv_ml;opencv_objdetect;opencv_photo;opencv_stitching;opencv_video;opencv_videoio;opencv_alphamat;opencv_aruco;opencv_bgsegm;opencv_bioinspired;opencv_ccalib;opencv_datasets;opencv_dnn_objdetect;opencv_dnn_superres;opencv_dpm;opencv_face;opencv_freetype;opencv_fuzzy;opencv_hfs;opencv_img_hash;opencv_intensity_transform;opencv_line_descriptor;opencv_mcc;opencv_optflow;opencv_phase_unwrapping;opencv_plot;opencv_quality;opencv_rapid;opencv_reg;opencv_rgbd;opencv_saliency;opencv_sfm;opencv_shape;opencv_stereo;opencv_structured_light;opencv_superres;opencv_surface_matching;opencv_text;opencv_tracking;opencv_videostab;opencv_viz;opencv_xfeatures2d;opencv_ximgproc;opencv_xobjdetect;opencv_xphoto
-- OpenCV_DIR = /usr/local/Cellar/opencv/4.5.0_1/lib/cmake/opencv4
Android
The following is the commands that I am using to build the Android dynamic library (.so). I have installed the NDK and am building for each ABI (x86, x86_64, armeabi-v7a, arm64-v8a).
cmake ../.. -DCMAKE_TOOLCHAIN_FILE=/Users/$USER/Library/Android/sdk/ndk-bundle/build/cmake/android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=21 -DANDROID_ABI=$abi_name -DBUILD_SHARED_LIBS=ON
cmake --build . --config Release
I directly get an error when building the library which is the following.
ld: error: /usr/local/Cellar/opencv/4.5.0_1/lib/libopencv_gapi.4.5.0.dylib: unknown file type
ld: error: /usr/local/Cellar/opencv/4.5.0_1/lib/libopencv_stitching.4.5.0.dylib: unknown file type
[...]
ld: error: /usr/local/Cellar/opencv/4.5.0_1/lib/libopencv_rapid.4.5.0.dylib: unknown file type
ld: error: too many errors emitted, stopping now (use -error-limit=0 to see all errors)
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
iOS
The following is the commands that I am using to build the iOS static library (.a). I am using leetal's ​cmake toolchain file from this repository.
cmake ../.. -G Xcode -DCMAKE_TOOLCHAIN_FILE=../../ios.toolchain.cmake -DPLATFORM=OS64COMBINED -DBUILD_SHARED_LIBS=OFF
cmake --build . --config Release
The compilation of the static library seems to work because no error message is printed. However, when the library is used in the final Xamarin solution, the linked library cannot be found and the following error is shown.
Native linking failed, undefined symbol: cv::Mat::deallocate(). Please verify that all the necessary frameworks have been referenced and native libraries are properly linked in. (MT5210)
Question
What am I missing in order to properly compile and link OpenCV into my C++ library ?
I am working on macOS Big Sur and uses the following tools versions:
cmake : 3.20.0-rc5
ndk : 23.0.7196353
apple clang : 12.0.0
I hope that the description of my problem is clear enough and I thank you in advance for any help.
We had same problems, including Xamarin's DllNotFoundException with message from last comment, which led me to this topic. What fixed the exception for us in the end was linking statically to OpenCV *.a libs instead of linking to the shared libopencv_java4.so file. So we now have a huge 30MB nativelib.so file for each android ABI in build output, instead of a pair of small nativelib.so and libopencv_java4.so per ABI. CMakeLists looks like this:
set( OpenCV_DIR "~/opencv/build/OpenCV-android-sdk/sdk/native/jni" )
find_package( OpenCV REQUIRED )
target_link_libraries( # Specifies the target library.
nativelib
${OpenCV_LIBS})
Another thing in our project is we use OpenCV optional modules and had to create a custom OpenCV build, which I guess ensures our native library and OpenCV are compiled against same NDK version. I suppose using the prebuilt OpenCV distribution and compiling against a different NDK version could lead to problems too otherwise.
I am trying to build an executable, and to change the link for boost library to static. The codes that I am trying to compile is here.
I am using Xubuntu 14.04, cmake 3.5.1, boost 1.54.
The error I got is:
Linking CXX shared library ../../lib/librexd.so
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/libboost_system.a(error_code.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/libboost_system.a: error adding symbols: Bad value
Things I have done:
Set boost library to static link in CMakeLists.txt (an example):
set(Boost_USE_STATIC_LIBS ON)
FIND_PACKAGE(Boost 1.46.0 COMPONENTS system regex program_options thread filesystem REQUIRED)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS})
TARGET_LINK_LIBRARIES(rexd ${Boost_LIBRARIES})
There are alot of CMakeLists.txt, so I did the above for 3 of them that uses Boost.
Next, I set the compiler flag to -fPIC for CMAKE_CXX_FLAGS and CMAKE_CXX_FLAGS_DEBUG, for example:
SET (CMAKE_CXX_FLAGS "-D_REENTRANT -fpic")
SET (CMAKE_CXX_FLAGS_DEBUG "-g -Wall -fpic")
Again, I did it for all CMakeLists that have CMAKE_CXX_FLAGS and CMAKE_CXX_FLAGS_DEBUG variables.
Lastly, I recompile boost with -fPIC option. I downloaded boost.tar.gz from sourceforge, extract it, and ran this:
bjam clean
bjam -d+2 link=static cxxflags="-fPIC" install
However, this does not seem to change anything. the date modification for libboost_system.a is dated a few years ago.
I have tried to tinker with add_library, making this static
ADD_LIBRARY(rexd STATIC ${sources_symbolic} ${sources_parsers} ${sources_lfit} ${sources_teacher} ${sources_rexd} ${sources_ippc_planner})
I got this error instead where it couldn't find a header .h:
No such file or directory
How should I proceed? I apologize if this question is too specific for my use case, but I can't find any other answers out there that I haven't tried.
My software that compiled fine on linux a few months ago stopped compiling on my new ubuntu:
Linking CXX executable myApp
/usr/bin/ld: ../libMyLib/libMyLib.a(MyFile.cpp.o): undefined reference to symbol '_ZN2cv6resizeERKNS_11_InputArrayERKNS_12_OutputArrayENS_5Size_IiEEddi'
/usr/bin/ld: note: '_ZN2cv6resizeERKNS_11_InputArrayERKNS_12_OutputArrayENS_5Size_IiEEddi' is defined in DSO /usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../lib/libopencv_imgproc.so so try adding it to the linker command line
/usr/lib/gcc/x86_64-linux-gnu/4.7/../../../../lib/libopencv_imgproc.so: could not read symbols: Invalid operation
collect2: error: ld returned 1 exit status
make[2]: *** [myApp/myApp] Error 1
make[1]: *** [myApp/CMakeFiles/myApp.dir/all] Error 2
make: *** [all] Error 2
I guess it's related to https://fedoraproject.org/wiki/UnderstandingDSOLinkChange.
My project (all cmake) contains several libraries and an application, both the libraries and the application depend on opencv and/or boost (each on some different ones). My own libraries are built as .a files, ocv/boost are pulled in as shared libraries, and the linking of the application then fails with above error.
I also tried to build my own libraries as SHARED but that resulted in even more errors. The CMakeLists of my libraries look like
FIND_PACKAGE(Boost REQUIRED)
FIND_PACKAGE(OpenCV REQUIRED core)
...stuff...
include_directories( ${OpenCV_INCLUDE_DIRS} )
include_directories( ${Boost_INCLUDE_DIRS} )
add_library( ${SUBPROJECT_NAME} ${SOURCE} ${HEADERS} )
The application CMakeLists looks like
FIND_PACKAGE( OpenCV REQUIRED core imgproc highgui)
include_directories( ${OpenCV_INCLUDE_DIRS} )
TARGET_LINK_LIBRARIES( ${SUBPROJECT_NAME} ${OpenCV_LIBS} MyLib )
That was all correct and I always thought that's the way to do it but now with this DSO stuff I just cannot get it to work anymore.
If relevant, I tried with CMake 2.8.7 and 2.8.10, and g++ 4.7.2 and 4.8, all produce the same errors.
GCC is very sensible to the order in which you specify libraries during the linking stage. For example, if libA.a depends on libB.a and an executable App depends on both, then you'd have to invoke linker in the following way:
gcc main.o object1.o ... object2.o -lA -lB -o App
NOTE: Pay attention to the fact that although A depends on B, still A goes before B. As a conclusion, the most independent artifact should be linked the last one. Sure that's counterintuitive in some sense, but try to treat it in the same way as the const qualifier is applied in C++. :)
Does OpenCV_LIBS contains -lopencv_imgproc?
If not, try to add manually -lopencv_imgproc the link command line (run make V=1)
If it works added it to TARGET_LINK