gcc - 如何编译混合的 C 和 C++ 代码?

标签 gcc compiler-construction makefile

我有一个 C++ 类,我想包含在 C 代码中,所以我写了一个包装器:

#ifndef __PMPC_CMPC__
#define __PMPC_CMPC__

#ifdef __cplusplus
extern "C"
#endif
void init_motor();

#ifdef __cplusplus
extern "C"
#endif
double* calc_cont_sig(double  * );

#endif

这是一个简单的测试
#include "cmpc_ekf.h"
#include <stdio.h>
int main(int argc, char* argv[]) {
    init_motor();
}

我尝试使用静态库来包含 C++ 代码,所以这是我的 Makefile:
all : main.o libcmpc_ekf.a
    gcc $(EFLAGS) $(CFLAGS) -static  -o main.out main.o  -L. -lcmpc_ekf

main.o: libcmpc_ekf.a
    gcc $(EFLAGS) $(CFLAGS) -static  -c main.c -L. -lcmpc_ekf

libcmpc_ekf.a: cmpc_ekf.o
    ar  rcs libcmpc_ekf.a  cmpc_ekf.o

cmpc_ekf.o: 
    g++ $(EFLAGS) $(CPPFLAGS) -c cmpc_ekf.cpp

clean:
    rm *.o main.out 

但是我收到以下错误(这只是错误代码中的一个标记)
cmpc_ekf.cpp:(.text+0x40): undefined reference to `std::cout'
cmpc_ekf.cpp:(.text+0x45): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'

如果我使用 g++创建二进制文件比一切正常。如何在不使用 g++ 的情况下将 C++ 类或库包含到 C 代码中或 -lstdc++当我创建二进制文件时?

最佳答案

在 C++ 应用程序中包含 C 代码很简单(正如您在使用 g++ 构建二进制文件时发现的那样)。但是,实际上并不支持采用其他方式。我不会说这是不可能的,但是您的“C”代码必须链接到 C++ 运行时,然后初始化 C++ 运行时空间。稍后,它也必须终止 C++ 运行时。我想不出有什么理由立即这样做。相反,只需将应用程序创建为 C++ 并链接到 C 代码,其运行时是 C++ 运行时的子集。

我应该澄清一下,所有这些意味着使用 C++ 编译器编译您的 C 代码。它会为您处理上述所有问题。

关于gcc - 如何编译混合的 C 和 C++ 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13960635/

相关文章:

performance - 替代 Flex 编译器

linux - 为什么可执行文件不接收 Makefile 中导出的变量?

无法在 Gnu-Make 中禁用 "default"后缀规则

c++ - eclipse cdt : calling make file from command line and adding version number

c - 请详细告诉我为什么c代码会这样?

编译错误大约 "expected specifier-qualifier-list before"

c - 如何在 C 中强制使用返回值

c - 如何使用目标文件中的函数

apache - 在 Solaris 11.3 中编译 httpd-2.4.20 make 失败

c++ - 单文件 Makefile 问题 : C++