我最终在 C 下大量填充了 C++...这是它的一般要点。 (顺便说一句,让 C++ 异常展开 C 堆栈可能会导致 C 代码出现问题,而这些问题不知道会发生此类事情......因此建议在 C++ 接口函数中执行一些 catch(...) 块。)
lib.h:一个头文件,它声明了一些具有 C 调用约定的函数,无论它是编译为 C 还是 C++
#pragma once
#if defined(__cplusplus)
extern "C" {
#endif
/* Looks like a typical C library interface */
struct c_class;
struct c_class *do_init();
void do_add(struct c_class *tgt, int a);
int do_get_size(const struct c_class *tgt);
void do_cleanup(struct c_class *tgt);
#if defined(__cplusplus)
}
#endif
lib.cpp:一个 C++ 库,其中包含一些使用 C 调用约定声明的函数
#include "lib.h"
#include <iostream>
#include <vector>
#include <cstdlib>
class Foo
{
std::vector<int> m_vec;
public:
Foo() : m_vec() {}
virtual ~Foo() {}
void add(int a) {
m_vec.push_back(a);
}
int getSize() {
return m_vec.size();
}
};
/* Exposed C interface with C++ insides */
extern "C" {
struct c_class
{
Foo *guts;
};
struct c_class *do_init()
{
struct c_class *obj = static_cast<c_class*>(malloc(sizeof(struct c_class)));
obj->guts = new Foo();
return obj;
}
void do_add(struct c_class *tgt, int a) {
tgt->guts->add(a);
}
int do_get_size(const struct c_class *tgt) {
return tgt->guts->getSize();
}
void do_cleanup(struct c_class *tgt) {
delete tgt->guts;
free(tgt);
}
}
main.c:使用从 lib 导出的 C 调用约定函数的 C 程序
#include <stdio.h>
#include "lib.h"
int main(int argc, char *argv[])
{
int i;
struct c_class *obj;
obj = do_init();
for(i = 0; i< 100; i++)
{
do_add(obj, i);
}
printf("Size: %d\n", do_get_size(obj));
do_cleanup(obj);
}
Makefile:将C编译为C,将C++编译为C++,然后使用C++编译器进行链接的makefile
CXXFLAGS ?= -Wall -Werror -pedantic
CFLAGS ?= -Wall -Werror -pedantic
.PHONY: all
all : test
test: lib.o main.o
$(CXX) $(CXXFLAGS) -o test lib.o main.o
lib.o: lib.cpp lib.h
$(CXX) $(CXXFLAGS) -c $< -o $@
main.o: main.c lib.h
$(CC) $(CFLAGS) -c $< -o $@
clean:
-rm lib.o main.o test
输出:
$ make
g++ -Wall -Werror -pedantic -c lib.cpp -o lib.o
cc -Wall -Werror -pedantic -c main.c -o main.o
g++ -Wall -Werror -pedantic -o test lib.o main.o
$ ./test
Size: 100