C、C++混合编程之extern "C"

为何要“混合编程”?举个例子:

CHeader.h

#ifndef C_HEADER_H
#define C_HEADER_H
void func();
#endif

CHeader.c

#include "CHeader.h"
#include <stdio.h>
void func()
{
    const unsigned char *str = "字符串";
    printf("%s\n", str);
}

CMain.c

#include "CHeader.h"
int main()
{
    func();
    return 0;
}

gcc -std=c11 CMain.c CHeader.c -o CMain,编译成功

Main.cpp

#include "CHeader.h"
int main()
{
    func();
    return 0;
}

g++ -std=c++11 CMain.c CHeader.c -o CMain,编译失败,错误信息:invalid conversion from 'const char*' to 'const unsigned char*' [-fpermissive] const unsigned char *str = "字符串";

这是因为在C++标准中char *与unsigned char *之间无法进行隐式地转换。

当然,将CHeader.c中的const unsigned char *str = "字符串";修改为const unsigned char *str = (const unsigned char *)"字符串";即可通过编译,

但本文重点是混合编程^_^

先用gcc编译CHeader.c:gcc -std=c11 CHeader.c -c,会得到CHeader.o,

然后用g++进行编译:g++ -std=c++11 Main.cpp CHeader.o -o Main,编译不通过,错误信息:undefined reference to 'func()',

这时extern "C"就派上用场了:将Main.cpp中的#include "CHeader.h"更改为

extern "C"
{
  #include "CHeader.h"
}

再次使用g++ -std=c++11 Main.cpp CHeader.o -o Main进行编译,编译成功

因为VC++会根据源文件扩展名区分是C还是C++,所以在使用VC++进行混合编程时仅需在C++代码中注明extern "C"即可调用C代码

猜你喜欢

转载自www.cnblogs.com/buyishi/p/9174226.html