Search code examples
c++gccboosthomebrewmacos-high-sierra

Why does my Boost Library fail to link?


I'm using a MacBook Pro, running MacOS 10.13.1; installed boost via homebrew using the following:

brew install boost --build-from-source

My code is the following:

#include <iostream>
#include <boost/filesystem.hpp>

namespace boostfs = boost::filesystem;

int main(int argc, char* argv[])
{
    if (argc <= 1) 
{
    std::cerr << "Usage: " << argv[0] << " <filename>" << std::endl;
    return 1;
}

boostfs::path p(argv[1]);

if (boostfs::exists(p))
{
    std::cout << "File " << p << " exists." << std::endl;
}
else 
{
    std::cout << "File " << p << " does not exist." << std::endl;
}

    return 0;
}

The error I am receiving is the following:

Undefined symbols for architecture x86_64:
"boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)", referenced from:
  boost::filesystem::exists(boost::filesystem::path const&) in chkfile-c30777.o
  "boost::system::system_category()", referenced from:
  ___cxx_global_var_init.2 in chkfile-c30777.o
  "boost::system::generic_category()", referenced from:
  ___cxx_global_var_init in chkfile-c30777.o
  ___cxx_global_var_init.1 in chkfile-c30777.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [chkfile] Error 1

I ran the code in the terminal using make and gcc 7.2.0.

I attempted the following:

g++ -std=c++17 -I /usr/local/include/ chkfile.cpp -o chkfile 

and got a new error:

Undefined symbols for architecture x86_64:
"boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)", referenced from:
boost::filesystem::exists(boost::filesystem::path const&) in cce7HDO8.o
"boost::system::system_category()", referenced from:
  __static_initialization_and_destruction_0(int, int) in cce7HDO8.o
"boost::system::generic_category()", referenced from:
  boost::system::error_category::std_category::equivalent(int, std::error_condition const&) const in cce7HDO8.o 

boost::system::error_category::std_category::equivalent(std::error_code const&, int) const in cce7HDO8.o
  __static_initialization_and_destruction_0(int, int) in cce7HDO8.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

What am I doing wrong?


Solution

  • Include filesystem this way

    #define BOOST_NO_CXX11_SCOPED_ENUMS
    #include <boost/filesystem.hpp>
    #undef BOOST_NO_CXX11_SCOPED_ENUMS
    

    Make sure you linked proper libraries

    -lboost_system -lboost_filesystem