arm64架构下Undefined symbols链接错误排查求助
问题:arm64架构下CMake链接错误,找不到UgWindow构造/析构函数符号
完整错误信息
Undefined symbols for architecture arm64: "ug::UgWindow::UgWindow(int, int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)" , referenced from: _main in main.cpp.o "ug::UgWindow::~UgWindow()" , referenced from: _main in main.cpp.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make[2]: *** [untitled-game] Error 1 make[1]: *** [CMakeFiles/untitled-game.dir/all] Error 2 make: *** [all] Error 2
相关代码文件
UgWindow头文件(ug_window.hpp)
#pragma once #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include <string> namespace ug { class UgWindow{ public: UgWindow(int w, int h, std::string name); ~UgWindow(); bool shouldClose(){ return glfwWindowShouldClose(window); } private: void initWindow(); const int width; const int height; std::string windowName; GLFWwindow *window; }; }
UgWindow源文件(ug_window.cpp)
#include "ug_window.hpp" namespace ug { UgWindow::UgWindow(int w, int h, std::string name): width{w}, height{h}, windowName{name} { initWindow(); } UgWindow::~UgWindow() { glfwDestroyWindow(window); glfwTerminate(); } void UgWindow::initWindow() { glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); window = glfwCreateWindow(width, height, windowName.c_str(), nullptr, nullptr); } }
CMake配置文件(CMakeLists.txt)
project(untitled-game) cmake_minimum_required(VERSION 3.22.4) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -std=c++17 " ) add_executable(${PROJECT_NAME} main.cpp) find_package(Vulkan REQUIRED) find_package(glfw3 3.3 REQUIRED) if (VULKAN_FOUND) message(STATUS "Found Vulkan, Including and Linking now") include_directories(${Vulkan_INCLUDE_DIRS}) target_link_libraries (${PROJECT_NAME} ${Vulkan_LIBRARIES} glfw) endif (VULKAN_FOUND)
解决方案
链接错误的核心原因是CMake没有把UgWindow的源文件加入编译流程:当前add_executable只指定了main.cpp,编译器不会自动扫描并编译其他源文件,导致UgWindow的构造/析构函数等实现没有生成对应的目标文件,链接阶段自然找不到符号。
修复步骤:
- 修改
CMakeLists.txt中的add_executable行,将UgWindow的源文件(假设文件名是ug_window.cpp)添加进去:
add_executable(${PROJECT_NAME} main.cpp ug_window.cpp)
- 建议改用更现代的CMake写法,替换全局的
include_directories为目标级别的target_include_directories(可选,但更规范):
# 替换原来的include_directories(${Vulkan_INCLUDE_DIRS}) target_include_directories(${PROJECT_NAME} PRIVATE ${Vulkan_INCLUDE_DIRS})
完成修改后,重新执行cmake和make命令,链接错误即可解决。
内容的提问来源于stack exchange,提问作者Blank
相关产品推荐
相关产品推荐

