使用Boost库构建失败

时间:2018-09-27 11:49:18

标签: c++ boost

我现在阅读了许多与此有关的问题,但似乎无法链接Boost库。这是我要运行的代码:

#include <iostream>
#include <ctime>
#include <vector>
#include <stdio.h>
#include <string>
#include <sstream>
#define BOOST_FILESYSTEM_VERSION 3
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>


namespace fs = ::boost::filesystem;



void getFilesInDir(const fs::path& root, const string& ext, vector<fs::path>& ret)
{
    if(!fs::exists(root) || !fs::is_directory(root)) return;

    fs::directory_iterator it(root);
    fs::directory_iterator endit;

    while(it != endit)
    {
        if(fs::is_regular_file(*it) && it->path().extension() == ext) ret.push_back(it->path().filename());
        ++it;

    }

}

尝试构建会导致许多错误,例如:

make all 
g++ -lm -g -Wall -std=c++11 -pthread -L/usr/lib/x86_64-linux-gnu/ -lboost_filesystem -lboost_system main.cpp -o main.out $(pkg-config opencv --cflags --libs)
/tmp/ccubp4VK.o: In function `getFilesInDir(boost::filesystem::path const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::vector<boost::filesystem::path, std::allocator<boost::filesystem::path> >&)':
/home/nettef/workspace/project//main.cpp:26: undefined reference to `boost::filesystem::path::extension() const'
/home/nettef/workspace/project//main.cpp:26: undefined reference to `boost::filesystem::path::filename() const'

我已三重检查,并且libboost_system.so中有libboost_filesystem/usr/lib/x86_64-linux-gnu/

这是制作目标:

CXX = g++
CXXFLAGS =  -lm -g -Wall -std=c++11 -pthread -L/usr/lib/x86_64-linux-gnu/ -lboost_filesystem -lboost_system

OPENCV_INCLUDES = $$(pkg-config opencv --cflags --libs)

TEST_LIBS = -lcppunit

CURRENT_DIR = $(shell pwd)

all:
    $(CXX) $(CXXFLAGS) main.cpp -o main.out $(OPENCV_INCLUDES)

1 个答案:

答案 0 :(得分:1)

您指定的链接器输入顺序错误。 main.cpp必须先于所需的库:

g++ -o main.out -Wall -std=c++11 -g main.cpp -lm -pthread -L/usr/lib/x86_64-linux-gnu/ -lboost_filesystem -lboost_system $(pkg-config opencv --cflags --libs)

您可能不需要标准连接器搜索路径中的-L/usr/lib/x86_64-linux-gnu/,请查看ld --verbose | grep SEARCH_DIR的输出。


我将以这种方式更改您的makefile:

CXX := g++
CXXFLAGS := -pthread -g -Wall -Wextra -std=c++11
LDFLAGS := -pthread -g
LDLIBS := -lm -lboost_filesystem -lboost_system
CPPFLAGS :=

OPENCV_INCLUDES := $(shell pkg-config opencv --cflags)
OPENCV_LDLIBS := $(shell pkg-config opencv --libs)

CURRENT_DIR = $(shell pwd)

all: main.out
.PHONY : all

main.out : LDLIBS += ${OPENCV_LDLIBS} -lcppunit
main.out : main.o
    $(CXX) -o $@ $(LDFLAGS) $^ ${LDLIBS}

main.o : CPPFLAGS += ${OPENCV_INCLUDES}
main.o : main.cpp
    ${CXX} -c -o $@ ${CPPFLAGS} ${CXXFLAGS} $<