如何在 autotools 中处理库的函数文件不是头文件? MWE

问题描述

所以最近我一直在尝试使用 autotools 来构建一个 C++ 库。最初我只是在处理纯自定义类,只需 #include 然后使用 g++ 进行编译非常容易。但是当我想为库编写一些自定义函数时,我了解到在头文件中编写函数是一种不好的做法,而是我应该在头文件中声明它,然后将它写在单独的 .cpp 文件中。后来我尝试使用 g++ ./lib/**/*.cpp src/main.cpp 成功编译。

所以基本上我的项目结构是代码放在src/下,标题放在include/下,函数放在lib/下。以下是我的src/Makefile.am

AUTOMAKE_OPTIONS = subdir-objects foreign
bin_PROGRAMS = main
include_HEADERS = -I../include/**/*.hpp 
main_SOURCES = -I../lib/**/*.cpp main.cpp

对于端点的目录(在 lib/ 下),我有如下内容

main_SOURCES = stdout.cpp

但是它给了我一个错误,没有名为main的程序,所以我想可能所有这些函数文件都必须先编译,所以我把它们改成了

noinst_PROGRAMS = stdout
stdout_SOURCES = stdout.cpp

但后来他们给了我以下错误

/usr/sbin/ld: /usr/lib/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../lib/Scrt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
collect2: error: ld returned 1 exit status

我知道错误意味着文件中没有写入 main(),但由于它是一个库函数文件,它并不意味着有 main(),它意味着被调用其他文件(如 main.cpp)。到这里我被卡住了。

我尝试在网上查找文档,但似乎其中大部分针对 C 程序而不是 C++,我不确定这些步骤是否兼容。我记得 C++ 库被编译成 .so.o 文件,而大多数教程似乎都使用 .la 文件。


MWE

src/main.cpp

#include"../include/conn/bash/stdout.hpp"
#include<string>
#include<iostream>

int main() {
        std::string  o=d::conn::bash::exec("ls");
        std::cout << o << std::endl;
        return 0;
}

include/conn/bash/stdout.hpp

#ifndef __CONN_BASH_O__
#define __CONN_BASH_O__
#include<string>
namespace d { namespace conn { namespace bash {
        std::string exec(const char*);
}}}
#endif

lib/conn/bash/stdout.cpp

#include"../../../include/conn/bash/stdout.hpp"
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

std::string d::conn::bash::exec(const char* cmd) {
    std::array<char,128> buffer;
    std::string result;
    std::unique_ptr<FILE,decltype(&pclose)> pipe(popen(cmd,"r"),pclose);
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    while (fgets(buffer.data(),buffer.size(),pipe.get()) != nullptr) {
        result += buffer.data();
    }
    return result;
}
// https://stackoverflow.com/a/478960/8460574

使用 g++ ./lib/**/*.cpp src/main.cpp

编译和测试

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)