• 用途:在C++中调用C语言文件
  • C++中有函数重载,会对函数名称做修饰,导致调用C语言的函数链接失败
  • 利用extern C可以解决问题
  • 方法1:
    在C++代码中加入
    告诉编译器 show函数用C语言方式 做链接
    //extern “C” void show();
  • 方法2:
    在C语言的头文件中加入6行代码
    #ifdef __cplusplus // 两个下划线 __ c plus plus
    extern “C” {
    #endif
    #ifdef __cplusplus // 两个下划线 __ c plus plus
    }
    #endif

test.h

#ifdef __cplusplus  // 两个下划线  __  c plus plus
extern "C" {
#endif

#include <stdio.h>

	void show();


#ifdef __cplusplus
}
#endif
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

test.c

#include "test.h"

void show()
{
	printf("hello world\n");
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

main.cpp

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include "test.h"


//告诉编译器  show函数用C语言方式 做链接
#include "test.h"
//extern "C" void show();




void test01()
{
	show();//_Z4showv;在C++中有函数重载会修饰函数名,但是show是c语言文件,因此链接失败
}



int main(){
	test01();


	system("pause");
	return EXIT_SUCCESS;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.