I'm trying to get a simple test program with yaml-cpp to run that looks like this:

// main.cpp

#include <iostream>
#include "yaml-cpp/yaml.h"

int main(int argc, const char *argv[])
{
     YAML::Node config = YAML::LoadFile("config.yaml");
     std::cout << config << std::endl;
}

I'm trying to compile with this command:

g++ -lyaml-cpp -L$(HOME)/local/yaml-cpp/build -I$(HOME)/local/yaml-cpp/include -std=c++11 main.cpp

and I'm getting an error that looks like this:

/tmp/ccz0D5ol.o: In function `main':
main.cpp:(.text+0xdd): undefined reference to `YAML::LoadFile(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: error: ld returned 1 exit status
make: *** [all] Error 1

Here's the g++ I'm using:

$ g++ --version
g++ (GCC) 5.4.0
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

This is on a linux machine where I don't have root access. I cloned the git repo to $HOME/local/yaml-cpp, created a build directory, ran cmake -DBUILD_SHARED_LIBS=ON .., then make, which created the file libyaml-cpp.so.0.6.2 and symlinks libyaml-cpp.so.0.6 and libyaml-cpp.so. My cmake is version 3.11.2 if that matters.

Not sure if this is helpful, but I first ran this problem by the maintainer of yaml-cpp as a github issue, and he said

It's likely a configuration error; you might be able to get an answer if you ask on Stack Overflow.

I also found a similar question with pretty much the exact same problem, but her solution of rearranging the order of the compile command didn't work for me. I get the same problem whether -lyaml-cpp is towards the beginning or the end of the command.

Any help would be appreciated.


@VTT 将我指向 cmake 和编译器的东西是正确的。当我查看原始命令的结果时cmake,前两行说

-- The C compiler identification is GNU 4.8.5
-- The CXX compiler identification is GNU 4.8.5

即使which gccwhich g++指向版本 5.4.0。我发现这个 SO answer指向这个 cmake FAQ page说你需要设置CCCXX环境变量来指定不同的编译器。所以我将我的 cmake 命令更改为:

CC=$(which gcc) CXX=$(which g++) cmake -DBUILD_SHARED_LIBS=ON ..

现在一切都很好。


你应该放在-lyaml-cpp命令行的末尾,之后main.cpp

@VTT 谢谢,但不幸的是,这是我尝试过的编译参数的众多安排之一。我只是再次尝试并得到相同的结果。

嗯,也许这是某种二进制不兼容。yaml库导出了哪些函数?yaml-cpp 是用编译的吗-std=c++11?

@VTT 虽然 when-lyaml-cpp之前main.cpp有一个额外的错误,看起来像这样:main.cpp:(.text+0x106): undefined reference to YAML::operator<<(std::ostream&, YAML::Node const&)' . This error goes away with the -lyaml-cpp` 在该行的末尾。不确定这是否意味着什么

@VTT 我不确定-std=c++11在编译 yaml-cpp 时是否使用了它。我在 Makefile 中找不到 g++。我将如何检查?