如何在 C 库的实现文件中使用 C++ STL 容器?

How can I use C++ STL containers in the implementation file of a C library?

说我希望在我希望 C 程序link 到...

的库的实现中使用 C++ STL 容器

我的例子header是

/* mynums.h */
#ifndef MY_NUMS
#define MY_NUMS

#ifdef __cplusplus
extern "C" {
#endif

void append_num(int num);
void print_nums();

#ifdef __cplusplus
}
#endif

#endif

而我的示例实现文件是

/* mynums.cpp */
#include "mynums.h"
#include <vector>

using std::vector;

vector<int> nums;

void append_num(int num)
{
    nums.push_back(num);
}

void print_nums()
{
    for (int i = 0; i < nums.size(); i++)
    {
        printf("%d, ", nums[i]);
    }
    printf("\n");
}

我的申请看起来像

/* app.c */
#include "mynums.h"

int main()
{
    append_num(1);
    append_num(2);
    append_num(3);
    print_nums();

    return 0;
}

我编译这些的命令是

# Compiles and runs
g++ -c -fpic -shared -std=c++0x -o libmynums.so mynums.cpp
g++ -L. -lmynums -o app app.c

# Library compiles, but the application fails
g++ -c -fpic -shared -std=c++0x -o libmynums.so mynums.cpp
gcc -L. -lmynums -o app app.c

我在尝试第二组编译命令时遇到的错误是我们 oh-so 熟悉的那些非常长的 stl 错误。一个例子是

./libmynums.so" In function 'void std:vector<int, std::allocator<int> >::_M_emplace_back_aux<int const&>(int const &)':
mynums.cpp:(.text._ZNSt6vectorIiSaIiEE19_M_emplace_back_auxIIRKiEEEvDpOT_[_ZNSt6vectorIiSaIiEE19_M_emplace_back_auxIIRKiEEEvDpOT_]+0x15d): undefined reference to '__cxa-begin_catch'

我希望能够使用 gcc 编译 link 我的示例应用程序代码到共享 object 库。这可能吗?如果是这样,那么我提供的代码/命令需要进行哪些更改?

问题是您实际上并没有创建共享库。您正在创建目标文件并将其命名为共享库。

gcc/g++ 的 -c 选项意味着只执行编译阶段。这导致 libmynums.so 成为目标文件。这就是为什么您可以通过 g++ 而不是 gcc link 访问它。

编译时去掉-c选项mynums.cpp你会得到一个共享库