C++ Cmake 链接库目标链接错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19478088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:52:57  来源:igfitidea点击:

Cmake link library target link error

c++openglcmakeglutglew

提问by Luffy

Hi I have problem with linkg Glfw and other libraries using cmake. From command line i compile like this

嗨,我在使用 cmake 链接 Glfw 和其他库时遇到问题。从命令行我像这样编译

g++ main.cpp -lGL -lGLU -lGLEW -lglfw

But I wanted to use cmake for compiling. I tried to use target_linkg_libraries but this produce error

但我想使用 cmake 进行编译。我尝试使用 target_linkg_libraries 但这会产生错误

CMake Error at CMakeLists.txt:18 (target_link_libraries): Cannot specify link libraries for target "GL" which is not built by this
project.

CMakeLists.txt:18 (target_link_libraries) 中的 CMake 错误:无法为不是由该
项目构建的目标“GL”指定链接库。

I tried do this using add definitions. I dont see error but this don't link libraries.

我尝试使用添加定义来做到这一点。我没有看到错误,但这不链接库。

cmake_minimum_required (VERSION 2.6)
project (test)

find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)

ADD_DEFINITIONS(
    -lGL
    -lGLU
    -lGLEW
    -lglfw
)

add_executable(test.out
    main.cpp
)

target_link_libraries(GL GLU GLEW glfw)

回答by Zifre

The syntax for target_link_librariesis:

的语法target_link_libraries是:

target_link_libraries(your_executable_name libraries_list)

And you don't have to add add_definitionstatements (target_link_librariesadds this options)

而且您不必添加add_definition语句(target_link_libraries添加此选项)

There are also some useful variables provided by OpenGL and GLEW packages.

OpenGL 和 GLEW 包也提供了一些有用的变量。

Your CMakeLists.txt should be like:

你的 CMakeLists.txt 应该是这样的:

cmake_minimum_required (VERSION 2.6)
project (test)

find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)

include_directories(${OPENGL_INCLUDE_DIR} ${GLEW_INCLUDE_DIRS})

add_executable(test
    main.cpp
)

target_link_libraries(test ${OPENGL_LIBRARIES} ${GLEW_LIBRARIES})

One important detail to keep in mind is to place the target_link_librariesafterthe add_executable(or add_library) line.

要记住的一个重要细节是在(或)行target_link_libraries之后放置。add_executableadd_library