尝试静态链接 Boost 时出现链接器错误

Linker errors when trying to statically linking Boost

我试图在我的程序中包含一个 Boost 库,但是我在静态链接我的程序时遇到了困难。即使我已将 -L/usr/include/boost/ -lboost_filesystem 添加到我的 makefile 中,我仍然收到一堆链接器错误。

例如,在编译期间我得到 undefined reference to boost::iostreams::detail::gzip_footer::reset()'

我的Boost版本是1.61.0.2,我是运行Ubuntu16.10(64位)和gcc版本6.2.0 20161005。我的boost库如accumulators, algorithms, ...是位于 /usr/include/boost,因此我的 makefile 如下所示:

CXX = g++
CXXFLAGS = -static -std=c++11 -Wall
LDFLAGS  = -L/usr/include/boost/ -lboost_filesystem
DEPFLAGS = -MM


SRC_DIR = ./src
OBJ_DIR = ./obj
SRC_EXT = .cpp
OBJ_EXT = .o

TARGET = main

SRCS := $(wildcard $(SRC_DIR)/*$(SRC_EXT))
OBJS := $(SRCS:$(SRC_DIR)/%$(SRC_EXT)=$(OBJ_DIR)/%$(OBJ_EXT))
DEP = depend.main


.PHONY: clean all depend

all: $(TARGET)

$(TARGET): $(OBJS)
    @echo "-> linking $@"
    @$(CXX) $^ $(LDFLAGS) -o $@

$(OBJ_DIR)/%$(OBJ_EXT) : $(SRC_DIR)/%$(SRC_EXT)
    @echo "-> compiling $@"
    @$(CXX) $(CXXFLAGS) -o $@ -c $<

clean:
    @echo "removing objects and main file"
    @rm -f $(OBJS) $(TARGET)  *.out  

$(SRC_DIR)/%.$(SRC_EXT): 
    $(CXX) $(DEPFLAGS) -MT \
    "$(subst $(SRC_DIR),$(OBJ_DIR),$(subst $(SRC_EXT),$(OBJ_EXT),$@))" \
    $(addprefix ,$@) >> $(DEP);

clear_dependencies:
    @echo "-> (re-)building dependencies";
    @$(RM) $(DEP)

depend: clear_dependencies $(SRCS)


-include $(DEP)

我正在尝试编译以下文件(在线找到的示例)

#include <fstream>
#include <iostream>

#include <boost/iostreams/filtering_stream.hpp>    
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>

namespace bo = boost::iostreams;

int main() 
{
    {
    std::ofstream ofile("hello.gz", std::ios_base::out | std::ios_base::binary);
    bo::filtering_ostream out;
    out.push(bo::gzip_compressor()); 
    out.push(ofile); 
    out << "This is a gz file\n";
    }

    {
    std::ifstream ifile("hello.gz", std::ios_base::in | std::ios_base::binary);
    bo::filtering_streambuf<bo::input> in;
    in.push(bo::gzip_decompressor());
    in.push(ifile);
    boost::iostreams::copy(in, std::cout);
    }
}

您的程序根本没有使用 libboost_filesystem。唯一的 它依赖的boost库是liboost_iostreams.