我正在尝试从docopt的github页面编译示例代码。我收到链接器错误:
/tmp/test-d3ed6b.o: In function `main':
test.cpp:(.text+0xf3): undefined reference to `docopt::docopt(std::string const&, std::vector<std::string, std::allocator<std::string> > const&, bool, std::string const&, bool)'
test.cpp:(.text+0x1c8): undefined reference to `docopt::operator<<(std::ostream&, docopt::value const&)'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我有一个
test.cpp
文件和一个带有所有docopt文件的目录docopt
。test.cpp
:#include <iostream>
#include "docopt/docopt.h"
static const char USAGE[] =
R"(Naval Fate.
Usage:
naval_fate ship new <name>...
naval_fate ship <name> move <x> <y> [--speed=<kn>]
naval_fate ship shoot <x> <y>
naval_fate mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate (-h | --help)
naval_fate --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
)";
int main(int argc, const char** argv)
{
std::map<std::string, docopt::value> args
= docopt::docopt(USAGE,
{ argv + 1, argv + argc },
true, // show help if requested
"Naval Fate 2.0"); // version string
for(auto const& arg : args) {
std::cout << arg.first << arg.second << std::endl;
}
return 0;
}
该错误是什么?我该如何解决?我已经尝试了clang-3.5和g++
最佳答案
我也遇到了这个问题。
我使用cmake
和CMakeLists.txt
中的某些特定配置解决了该问题。以下配置对我有用:
cmake_minimum_required (VERSION 3.5)
project(my_project)
include(ExternalProject)
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )
set(DOCOPT_ROOT ${PROJECT_SOURCE_DIR}/external/docopt)
set(DOCOPT_INCLUDE_DIRS ${DOCOPT_ROOT}/include/docopt)
set(DOCOPT_LIBRARIES ${DOCOPT_ROOT}/lib/libdocopt.a)
set(docopt_INSTALL_DIR "${DOCOPT_ROOT}")
set(docopt_CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${docopt_INSTALL_DIR})
ExternalProject_Add(docopt
PREFIX ${DOCOPT_ROOT}
GIT_REPOSITORY https://github.com/docopt/docopt.cpp.git
BINARY_DIR ${DOCOPT_ROOT}
INSTALL_DIR ${DOCOPT_ROOT}
CMAKE_ARGS ${docopt_CMAKE_ARGS}
LOG_DOWNLOAD ON
LOG_CONFIGURE ON
LOG_BUILD ON
LOG_INSTALL ON
)
add_library(libdocopt STATIC IMPORTED)
set_target_properties(libdocopt PROPERTIES IMPORTED_LOCATION ${DOCOPT_LIBRARIES})
add_dependencies(libdocopt docopt)
include_directories(${PROJECT_SOURCE_DIR})
include_directories(${DOCOPT_INCLUDE_DIRS})
file(GLOB projector_src
"*.h"
"*.cpp"
)
add_executable(my_project ${my_project_src})
target_link_libraries(projector libdocopt)
显然,您不需要使用
cmake
,而是需要使用自己的代码放入docopt.cpp
的源代码,否则您需要告诉链接器在哪里寻找它。 cmake
确实为您解决了这一问题,但这是您还要担心的另一件事。