我的项目如下所示:
include/util/safety.h
include/opcodes/8bit_load_opcodes.h
include/CPU.h
src/util/safety.cpp
src/CPU.cpp
src/main.cpp
src/opcodes/8bit_load_opcodes.cpp
CMakeLists.txt
使用下面的 CMake 脚本
cmake_minimum_required(VERSION 3.17)
project(gameboy)
enable_testing()
FIND_PACKAGE(Boost 1.65.1 COMPONENTS unit_test_framework REQUIRED)
if(NOT Boost_FOUND)
message(FATAL_ERROR "Boost Not found")
endif()
set(CMAKE_CXX_STANDARD 20)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include)
INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include/opcodes)
INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include/util)
ADD_LIBRARY(cpu_util src/util/safety.cpp)
ADD_LIBRARY(cpu src/CPU.cpp src/opcodes/8bit_load_opcodes.cpp)
TARGET_LINK_LIBRARIES(cpu ${Boost_LIBRARIES})
TARGET_LINK_LIBRARIES(cpu cpu_util)
add_executable(gameboy src/main.cpp)
TARGET_LINK_LIBRARIES(gameboy cpu)
当我运行make
时我得到:
Scanning dependencies of target cpu_util
[ 14%] Building CXX object CMakeFiles/cpu_util.dir/src/util/safety.cpp.o
[ 28%] Linking CXX static library libcpu_util.a
[ 28%] Built target cpu_util
Scanning dependencies of target cpu
[ 42%] Building CXX object CMakeFiles/cpu.dir/src/CPU.cpp.o
[ 57%] Building CXX object CMakeFiles/cpu.dir/src/opcodes/8bit_load_opcodes.cpp.o
[ 71%] Linking CXX static library libcpu.a
[ 71%] Built target cpu
Scanning dependencies of target gameboy
[ 85%] Building CXX object CMakeFiles/gameboy.dir/src/main.cpp.o
[100%] Linking CXX executable gameboy
CMakeFiles/gameboy.dir/src/main.cpp.o: In function `main':
/home/cedric/Programming/gameboy/src/main.cpp:6: undefined reference to `unsigned short validate_argument<unsigned short>(unsigned short, unsigned short)'
collect2: error: ld returned 1 exit status
CMakeFiles/gameboy.dir/build.make:106: recipe for target 'gameboy' failed
make[2]: *** [gameboy] Error 1
CMakeFiles/Makefile2:154: recipe for target 'CMakeFiles/gameboy.dir/all' failed
make[1]: *** [CMakeFiles/gameboy.dir/all] Error 2
Makefile:114: recipe for target 'all' failed
make: *** [all] Error 2
正在运行nm
似乎显示空输出:
$ nm libcpu_util.a
safety.cpp.o:
为什么 libcpu_util 中没有任何符号以及如何修复此 make 错误?
供引用:
安全.cpp
#include <stdexcept>
#include "util/safety.h"
template<typename T>
T validate_argument(T value, T mask)
{
if((value & mask) != value)
throw std::runtime_error("Value outside of mask!");
return value;
}
安全.h
#ifndef GAMEBOY_SAFETY_H
#define GAMEBOY_SAFETY_H
template<typename T>
T validate_argument(T value, T mask);
#endif //GAMEBOY_SAFETY_H
最佳答案
safety.h
只有一个模板函数,并且定义部分位于safety.cpp
中,这是错误的。模板函数应该在 header 中定义,因此您在这里会得到一个空库。我们需要将定义部分放在头文件中,并删除库libcpu_util.a
template<typename T>
T validate_argument(T value, T mask);
关于c++ - 创建的 CMake 静态库没有符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68028860/