我正在尝试编写一个可以从 C 调用的 C++ 库。但是,每当我尝试编写一个最小的示例时,它都会因未定义的引用而崩溃。这是我的代码:
图书馆.h
#ifndef __MY_CPP_THING_H
#define __MY_CPP_THING_H
#ifdef __cplusplus
extern "C" {
#endif
void printSomething();
#ifdef __cplusplus
}
#endif
#endif
图书馆.cpp
#include <iostream>
#include "mylibrary.h"
extern "C" {
void printSomething() {
std::cout << "PLEASE PRINT\n";
}
}
主程序
#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
(链接静态库并编译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
有关如何解决错误的任何建议?