【问题标题】:CMake: Undefined reference to functionCMake:对函数的未定义引用
【发布时间】:2012-10-07 11:04:42
【问题描述】:

我有以下目录结构:

   ├── build (empty dir)
   ├── CMakeLists.txt
   ├── easylogging++.h
   ├── help.h
   ├── operation.h
   ├── operation_list.h
   ├── operations
   │   ├── CMakeLists.txt
   │   ├── matchcount.cc
   │   └── matchcount.h
   └── ops_toolkit.cc

我是 CMake 的新手,正在尝试编写 CMakeLists.txt。 我的 matchcount.h 有一个签名,其实现在 matchcount.cc 中(作为典型的 C/C++ 结构)。 以下是我在基目录中的 CMakeLists.txt

cmake_minimum_required(VERSION 2.6)
project(ops_toolkit)

add_subdirectory(operations)

add_executable(ops_toolkit ops_toolkit.cc)
set(CMAKE_CXX_FLAGS "-std=c++0x")

以下是操作目录中的一个

include_directories(${ops_toolkit_SOURCE_DIR}/operations)
link_directories(${ops_toolkit_BINARY_DIR}/operations)
set(all_operations_HEADER operations/matchcount.h)
set(all_operations_SOURCES operations/matchcount.cc)

我得到了名为 int matchcount(int, const char**) 的函数签名的未定义引用,并提出以下投诉

dev:~/work/ops_toolkit/build$ make
Scanning dependencies of target ops_toolkit
[100%] Building CXX object CMakeFiles/ops_toolkit.dir/ops_toolkit.cc.o
Linking CXX executable ops_toolkit
CMakeFiles/ops_toolkit.dir/ops_toolkit.cc.o: In function `__static_initialization_and_destruction_0(int, int)':
ops_toolkit.cc:(.text+0x249): undefined reference to `operations::matchcount(int, char const**)'
collect2: ld returned 1 exit status
make[2]: *** [ops_toolkit] Error 1
make[1]: *** [CMakeFiles/ops_toolkit.dir/all] Error 2
make: *** [all] Error 2

有人可以帮我解决这个问题吗? 谢谢

【问题讨论】:

  • 你是否实现了操作::matchcount(int, char const**)?
  • @LuchianGrigore 那是另一回事,我没有这个签名的声明或定义,我有操作::matchcount(int, const char**)。是的,我在 matchcount.cc 中实现了它
  • char const**const char** 相同。 matchcount 是一个项目吗?
  • @Synxis 不,匹配计数只包含一堆函数项目名称是根 CMakeList 中定义的 ops_toolkit

标签: c++ c compilation


【解决方案1】:

问题来自add_subdirectory 及其关联的CMakeLists.txt(./operations 中的那个),这是不正确的,请参阅this SO question for the implications of the add_subdirectory command

为了清楚起见,我还建议您将 include_directorieslink_directories 放在主 CMake 文件中。

【讨论】:

  • 所以在主 CMake 文件中包含和链接目录就足够了,我们不必将它们包含在子目录中(除非有第 3 级深度目录)?如果是,子 CMake 文件究竟应该包含什么?
  • 子目录应该用于子项目(只是带有projectinclude_directories 等的普通 CMake 文件)或模块(只是父范围内的 set 变量,如源代码、标头和其他配置)。
猜你喜欢
  • 2012-10-14
  • 1970-01-01
  • 2020-06-26
  • 2015-12-06
  • 2018-01-01
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多