创建的 CMake 静态库没有符号

Created CMake static library has no symbols

我的项目是这样的:

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 错误?

供参考:

safety.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;
}

safety.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,这是错误的。模板函数应该在头文件中定义,所以你在这里得到一个空库。我们需要把定义部分放在头文件中,去掉库libcpu_util.a

template<typename T>
T validate_argument(T value, T mask);