我尝试使用CMake编译项目,但我得到了对我创建的类函数的未定义引用。如果我手工创建一个Makefile,一切都编译得很好。但是当我使用CMake时,我收到undefined reference
错误。
这是目录结构:
.
├── build
├── CMakeLists.txt
├── info
│ ├── indexer.pdf
│ └── search.pdf
├── Makefile
├── sample
│ ├── 1
│ │ └── b.txt
│ ├── 2
│ │ └── c.txt
│ ├── 3
│ │ └── d.txt
│ └── a.txt
├── src
│ ├── cpp
│ │ ├── index.cpp
│ │ └── record.cpp
│ ├── h
│ │ ├── index.h
│ │ └── record.h
│ └── main.cpp
├── tests
│ └── a
└── todo.txt
CMakeLists.txt
:
cmake_minimum_required(VERSION 2.8)
# Project Name
PROJECT(indexer CXX)
# Binary dir
# Built in CMake variables:
# CMAKE_SOURCE_DIR: the directory where cmake was executed
# CMAKE_BINARY_DIR: where the output will go
# EXECUTABLE_OUTPUT_PATH: common place to put executables if you don't want it to be CMAKE_BINARY_DIR
# LIBRARY_OUTPUT_PATH: common place to put libraries if you don't want it to be CMAKE_BINARY_DIR
set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/build)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})
# Add additional compiler flags
# Built-ins:
# - CMAKE_CXX_FLAGS_DEBUG = -g
# - CMAKE_CXX_FLAGS_RELEASE = -O3 -NDEBUG
set(CMAKE_CXX_FLAGS "-std=c++0x -Wall")
include_directories("${PROJECT_SOURCE_DIR}/src/h")
# Aggregate the sources
file(GLOB SOURCES "${PROJECT_SOURCE_DIR}/src/cpp")
add_executable(indexer "${PROJECT_SOURCE_DIR}/src/main.cpp" ${SOURCES})``
错误:
CMakeFiles/indexer.dir/src/main.cpp.o: In function `parse(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, Index*)':
main.cpp:(.text+0x1b5): undefined reference to `Record::Record(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)'
main.cpp:(.text+0x1ee): undefined reference to `Index::add(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, Record)'
CMakeFiles/indexer.dir/src/main.cpp.o: In function `main':
main.cpp:(.text+0x77d): undefined reference to `Index::Index()'
main.cpp:(.text+0x84b): undefined reference to `Index::print()'
collect2: error: ld returned 1 exit status
CMakeFiles/indexer.dir/build.make:94: recipe for target 'indexer' failed
make[2]: *** [indexer] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/indexer.dir/all' failed
make[1]: *** [CMakeFiles/indexer.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
有人可以告诉我我在这里做错了吗?
答案 0 :(得分:1)
您的问题在于
行file(GLOB SOURCES "${PROJECT_SOURCE_DIR}/src/cpp")
这会将SOURCES
变量设置为cpp
目录中名为src
的文件。我认为你的意思是
file(GLOB SOURCES "${PROJECT_SOURCE_DIR}/src/cpp/*.cpp")
这将捕获所有以扩展名.cpp
结尾的文件,并将其放入SOURCES
变量。
注意:我认为您不需要将"${PROJECT_SOURCE_DIR}/src/main.cpp"
作为参数传递给create_executable
,因为您的SOURCES
变量应该已包含main.cpp
。