- extern “C” 的主要作用就是 为了能够正确实现 C++ 代码调用其他C语言代码。加上 extern “C” 后,会指示编译器这部分代码按C语言的进行编译,而不是C++的。由于C++支持 函数重载,因此编译器编译函数的过程中会将 函数的参数类型 也加到编译后的代码中,而不仅仅是函数名;而C语言并不支持函数重载,因此编译C语言代码的函数时不会带上函数的参数类型,一般只包括 函数名。
- 代码演示:
- C++头文件 cppExample.h
#ifndef CPP_EXAMPLE_H #define CPP_EXAMPLE_H extern "C" int add( int x, int y ); #endif - C++实现文件 cppExample.cpp
#include "cppExample.h" int add( int x, int y ) { return x + y; } - C实现文件 cFile.c
/* 这样会编译出错:#include "cppExample.h" */ extern int add( int x, int y ); int main( int argc, char* argv[] ) { add( 2, 3 ); return 0; }
- C++头文件 cppExample.h
- 本文主要摘抄百度百科 extern “C”
C++中 extern “c“ 的作用
最新推荐文章于 2025-02-12 20:46:09 发布

419

被折叠的 条评论
为什么被折叠?



