Search code examples
c++yaml-cpp

How to link a .a file in C++


I'm trying to get the yaml-cpp parser working on my computer. I followed the instructions on the README, which generated the file libyaml-cpp.a with no errors or warnings. Then I copied that file into a directory, let's call it /path/to/files, where I also put b.yaml, and main.cpp, which contains the following text:

// main.cpp

int main(int argc, const char *argv[])
{
  YAML::Node config = YAML::LoadFile("b.yaml");
  return 0;
}

This comes from the first line of the yaml-cpp tutorial. I tried compiling this while linking to the yaml-cpp library in a few different ways, all of which lead to the same compile-time error: use of undeclared identifier 'YAML'. Here are some of the things I tried:

  1. g++ main.cpp -lyaml-cpp -L/path/to/files
  2. g++ main.cpp libyaml-cpp.a
  3. g++ main.cpp libyaml-cpp.a -lyaml-cpp -L/path/to/files

and so on. How do I compile this correctly or more properly debug this process?

==EDIT==

Now my main.cpp file looks like this:

// main.cpp

#include <iostream>
#include "yaml.h"

int main(int argc, const char *argv[])
{
  YAML::Node config = YAML::LoadFile("b.yaml");
  return 0;
}

Here's my compile command and error message:

$ g++ main.cpp -lyaml-cpp -I/Users/benlindsay/scratch/yaml-cpp/include -L/Users/benlindsay/scratch/yaml-cpp/build
main.cpp:10:3: error: use of undeclared identifier 'YAML'
  YAML::Node config = YAML::LoadFile("b.yaml");
  ^
main.cpp:10:23: error: use of undeclared identifier 'YAML'
  YAML::Node config = YAML::LoadFile("b.yaml");
                      ^
2 errors generated.
make: *** [a.out] Error 1

/Users/benlindsay/scratch/yaml-cpp/include contains a yaml-cpp directory, which in turn contains all the .h files including yaml.h. /Users/benlindsay/scratch/yaml-cpp/build contains the lyaml-cpp.a file.


Solution

  • Ok, I downloaded yaml-cpp and tried out, Here is a working version

    #include <iostream>
    #include "yaml-cpp/yaml.h" //You need to prepend the yaml-cpp
    
    int main(int argc, const char *argv[])
    {
         YAML::Node config = YAML::LoadFile("b.yaml");
         //return 0; In cpp, return 0 is not required on main, hence commented
    }
    

    The compile using g++ -std=c++11 main.cpp -lyaml-cpp -I/Users/benlindsay/scratch/yaml-cpp/include -L/Users/benlindsay/scratch/yaml-cpp/build