无法从 C 无错误地调用 C++ 代码

Cannot Call C++ Code from C without Error

我正在尝试编写一个可以从 C 调用的 C++ 库。但是,每当我尝试编写一个最低限度的示例时,它都会因未定义的引用而崩溃。这是我的代码:


mylibrary.h

#ifndef __MY_CPP_THING_H
#define __MY_CPP_THING_H

#ifdef __cplusplus
extern "C" {
#endif

void printSomething();

#ifdef __cplusplus
}
#endif

#endif

mylibrary.cpp

#include <iostream>

#include "mylibrary.h"

extern "C" {

void printSomething() {
    std::cout << "PLEASE PRINT\n";
}

}

main.c

#include "mylibrary.h"

int main() {
    printSomething();
    return 0;
}

编译过程是这样的:

g++ -c mylibrary.cpp -o mylibrary.o(创建"mylibrary.o")

ar rcs libmylibrary.a mylibrary.o(创建静态库"libmylibrary.a")

gcc main.c -L. -lmylibrary(link静态库和编译C源文件)

但是,我收到了这个错误转储:

mylibrary.o:mylibrary.cpp:(.text+0x17): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
mylibrary.o:mylibrary.cpp:(.text+0x32): undefined reference to `std::ios_base::Init::~Init()'
mylibrary.o:mylibrary.cpp:(.text+0x62): undefined reference to `std::ios_base::Init::Init()'
mylibrary.o:mylibrary.cpp:(.rdata$.refptr._ZSt4cout[.refptr._ZSt4cout]+0x0): undefined reference to `std::cout'
collect2.exe: error: ld returned 1 exit status

关于如何解决错误有什么建议吗?

mylibrary.o 仍然依赖于 C++ 标准库,gcc 不知道。在最后一步用 -lstdc++ 调用 gcc

创建动态库而不是静态库应该可以解决问题:

$ gcc -c main.c
$ g++ -fPIC -shared -o mylibrary.so mylibrary.cpp
$ gcc -o main main.o mylibrary.so

然后:

$ LD_LIBRARY_PATH=".:${LD_LIBRARY_PATH}" ./main
PLEASE PRINT

与 :

$ objdump -p main | grep NEEDED
  NEEDED               mylibrary.so
  NEEDED               libc.so.6
$ objdump -p mylibrary.so | grep NEEDED
  NEEDED               libstdc++.so.6
  NEEDED               libc.so.6