简体   繁体   English

如何在cmake中链接静态库

[英]How to link static libraries in cmake

I am trying to link GLFW in my project.我正在尝试在我的项目中链接 GLFW。 There is screenshot of my project structure:有我的项目结构的截图: 在此处输入图片说明

This is my CMakeLists.txt:这是我的 CMakeLists.txt:

cmake_minimum_required(VERSION 3.15)
project(testo)

set(CMAKE_CXX_STANDARD 17)

add_executable(testo main.cpp)
add_library(glfw3 STATIC main.cpp)

include_directories(lib/glfw/include/)

find_library(GLFW glfw3 lib/glfw/lib)
target_link_libraries(testo LINK_PUBLIC ${GLFW})

Howewer, when i try to run project in clion, it gives me error:然而,当我尝试在 clion 中运行项目时,它给了我错误:

====================[ Build | testo | Debug ]===================================
"C:\Program Files\JetBrains\CLion 2019.2.5\bin\cmake\win\bin\cmake.exe" --build C:\Users\Student\testo\cmake-build-debug --target testo -- -j 2
[ 50%] Linking CXX executable testo.exe
CMakeFiles\testo.dir/objects.a(main.cpp.obj): In function `main':
C:/Users/Student/testo/main.cpp:5: undefined reference to `glfwInit'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\testo.dir\build.make:87: testo.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:77: CMakeFiles/testo.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:84: CMakeFiles/testo.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: testo] Error 2

Here is some github example .这是一些github 示例
Here is some SO question you are duplicating .这是您正在复制的一些 SO 问题

Based on that this should look like this:基于此,这应该是这样的:

cmake_minimum_required(VERSION 3.15)
project(testo)

set(CMAKE_CXX_STANDARD 17)

find_package(GLEW REQUIRED)

add_executable(testo main.cpp)
target_link_libraries(testo PUBLIC ${GLEW_LIBRARIES})
target_include_directories(testo PUBLIC ${GLEW_INCLUDE_DIRS})

I think this has something to do with linux adding "lib***.a" [pre/post]fix to the lib filename.我认为这与 linux 将"lib***.a" [pre/post] 修复程序添加到 lib 文件名有关。

Try adding your lib/glfw/lib directory to your link_directories() just as you do with your include_dicrectories() .尝试将您的lib/glfw/lib目录添加到您的link_directories() ,就像您对include_dicrectories()所做的一样。

Also, add_library() specifies you are trying to compile glfw3 by yourself, but what you tried doing is to only link with it.此外, add_library()指定您正在尝试自己编译glfw3 ,但您尝试做的只是与其链接。 I've removed it for you.我已经为你删除了。

cmake_minimum_required(VERSION 3.15)
project(testo)

set(CMAKE_CXX_STANDARD 17)

add_executable(testo main.cpp)

include_directories(lib/glfw/include/)
link_directories(lib/glfw/lib)

target_link_libraries(testo LINK_PUBLIC glfw3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM