英文:
CMake gives undefined reference even if use `link_libraries` command
问题
我正在尝试使用Git子模块链接GLFW。以下是我的CMakeLists.txt
:
cmake_minimum_required(VERSION 3.0.0)
project(guitest VERSION 0.1.0 LANGUAGES C CXX)
add_executable(guitest main.cpp)
add_subdirectory(glfw)
include_directories(glfw/include)
link_directories(glfw/src)
link_libraries(glfw)
在CMake中我没有收到任何错误,但当我尝试构建我的项目时,我收到以下错误信息:
[build] C:/Users/Konstantin/Documents/sasha/guitest/main.cpp:7: undefined reference to `glfwInit'
以下是我的代码:
#include <iostream>
#include <GLFW/glfw3.h>
int main(int, char**){
GLFWwindow *window;
if(!glfwInit()){
std::cout << "Init failure!" << std::endl;
exit(EXIT_FAILURE);
}
}
我正在使用Visual Studio Code和GCC 6.3.0 MinGW编译器工具链。
英文:
I'm trying to link GLFW using git submodule. Here is my CMakeLists.txt
:
cmake_minimum_required(VERSION 3.0.0)
project(guitest VERSION 0.1.0 LANGUAGES C CXX)
add_executable(guitest main.cpp)
add_subdirectory(glfw)
include_directories(glfw/include)
link_directories(glfw/src)
link_libraries(glfw)
I get no errors in CMake, but when I try to build my project I get
[build] C:/Users/Konstantin/Documents/sasha/guitest/main.cpp:7: undefined reference to `glfwInit'
Here is my code
#include <iostream>
#include <GLFW/glfw3.h>
int main(int, char**){
GLFWwindow *window;
if(!glfwInit()){
std::cout << "Init failure!"<<std::endl;
exit(EXIT_FAILURE);
}
}
I'm using Visual Studio Code and GCC 6.3.0 MinGW compiler kit.
答案1
得分: 3
The command link_libraries
affects only on targets which are created after. Since your call to add_executable
precedes link_libraries
, your executable is not linked.
Correct (but not the best):
add_subdirectory(glfw)
link_libraries(glfw)
add_executable(guitest main.cpp)
It is preferred to use target_link_libraries
instead of link_libraries
.
add_subdirectory(glfw)
add_executable(guitest main.cpp)
target_link_libraries(guitest PRIVATE glfw)
In both cases include_directories
call could be omitted, since linkage with glfw target also ships your executable with GLFW include directories.
英文:
The command link_libraries
affects only on targets which are created after. Since your call to add_executable
precedes link_libraries
, your executable is not linked.
Correct (but not the best):
add_subdirectory(glfw)
link_libraries(glfw)
add_executable(guitest main.cpp)
It is preferred to use target_link_libraries
instead of link_libraries
.
add_subdirectory(glfw)
add_executable(guitest main.cpp)
target_link_libraries(guitest PRIVATE glfw)
In both cases include_directories
call could be omitted, since linkage with glfw target also ships your executable with GLFW include directories.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论