C++ extern “C”

作者 : admin 本文共656个字,预计阅读时间需要2分钟 发布时间: 2024-06-8 共4人阅读

文章目录

  • 一、c的extern
  • 二、cpp中的extern “C”
  • 三、cpp动态链接库

一、c的extern

c语言的extern关键字作用是说明“此变量/函数是在别处定义的,要在此处引用”。

二、cpp中的extern “C”

1、c与cpp的编译规则不同,extern “C”告诉cpp编译器已c的风格编译代码。
2、cpp调用c的函数时,除了声明extern “C”外还要在c文件添加宏定义。

/**********A.h*****************/
#ifndef A_H
#define A_H

#ifdef __cplusplus
extern "C" {
#endif

	int foo(int x, int y);

	class A;
#ifdef __cplusplus
}
#endif

#endif
/*********************A.cpp*************************/
#include "A.h"
int foo(int x, int y) {
	return x + y;
}

class A {
	int a;
};
/**********************B.cpp**********************************/
extern "C" {
	#include "A.h"
}
#include


int main() {
	std::cout << foo(1, 2);
}

三、cpp动态链接库

extern "C" __declspec(dllimport) className * _stdcall geObjFun();

VS编译动态链接库供其他语言使用时使用到的命令。

本站无任何商业行为
个人在线分享 » C++ extern “C”
E-->