登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

中吴南顾惟一笑

成功法则就是那19个字

 
 
 

日志

 
 

usage of extern “C” { //code }  

2010-08-18 14:24:47|  分类: R&D |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

You need to use extern "C" in C++ when declaring a function that was implemented/compiled in C. The use of extern "C" tells the compiler/linker to use the C naming and calling conventions, instead of the C++ name mangling and C++ calling conventions that would be used otherwise. For functions provided by other libraries, you will almost never need to use extern "C", as well-written libraries will already have this in there for the public APIs that it exports to both C and C++. If, however, you write a library that you want to make available both in C and in C++, then you will have to conditionally put that in your headers.

1. If you have a function implemented in C and want to call it from C++.
1.1). if you can modify C header files
Typically the declarations in a C header file are surrounded with

#ifdef __cplusplus
extern "C" {
#endif
 
[... C declarations ...]
 
#ifdef __cplusplus
}
#endif
to make it usable from C++.

 

1.2). if you cannot modify C header files

include the header files in C++ source files
extern "C" {
/* include c library header */
}

or wrap the necessary c headers in a seperate header file then include it
#ifdef __cplusplus
extern "C" {
#endif
 
/* include c library header */
 
#ifdef __cplusplus
} // extern
#endif


1.3). If you only want to call several C functions, and for some reason you don't have or don't want to #include a C header file in which that function is declared, you can declare the individual C function in your C++ code using the extern "C"

syntax.

extern "C" {
   [... function declarations...]
 }

After this you simply call the function just as if it were a C++ function

 

2. If you have a function implemented in C++ and want to call it from C.

 // This is C++ code
 
 // Declare  using extern "C":
 extern "C" void cplusplus_func_name(paramlist);
  ...
  // Define function in some C++ module:
 void cplusplus_func_name(paramlist)
 {
   ...
 }

The extern "C" line tells the compiler that the external information sent to the linker should use C calling conventions and name mangling (e.g., preceded by a single underscore). Since name overloading isn't supported by C, you can't make several overloaded functions simultaneously callable by a C program.

  评论这张
 
阅读(595)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018