我现在阅读了许多与此有关的问题,但似乎无法链接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/

这是make目标:
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)

最佳答案

您以错误的顺序指定了链接器输入。 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} $<

10-08 08:33