简体   繁体   English

C ++:extern和inline函数

[英]C++: extern and inline functions

I have a couple of files written in C, and I want them to be C++-compatible, so for my C headers I use; 我有几个用C语言编写的文件,我希望它们与C ++兼容,所以对于我使用的C头文件;

#ifdef __cplusplus
extern "C" {
#endif

at the beginning of the file and of course 在文件的开头,当然

#ifdef __cplusplus
}
#endif

...at the end. ...在末尾。 But it seems to create problems with the 'inline' keyword. 但它似乎会产生'inline'关键字的问题。 My solution is to simply remove the inline keyword for C++, but I guess it could have a bad effect on C++ programs (these functions are called gazillions of times). 我的解决方案是简单地删除C ++的inline关键字,但我想它可能会对C ++程序产生不良影响(这些函数被称为gazillions of times)。

Is there a better solution ? 有更好的解决方案吗?

If I understand correctly, I would do: 如果我理解正确,我会这样做:


 #ifdef __cplusplus
 #define D_INLINE static
 extern "C" {
 #else
 #define D_INLINE inline
 #endif

And use the D_INLINE for the functions that I think should need inline. 并使用D_INLINE作为我认为应该内联的函数。 As delnan said, the compiler will optimize it anyway and the inline keyword is just a hint to the compiler that the programmer thinks that the compiler should inline the function. 正如delnan所说,编译器无论如何都会优化它,而inline关键字只是编译器的一个提示,程序员认为编译器应该内联函数。 It doesn't force the compiler to inline the function. 它不会强制编译器内联函数。

Inline functions are expected to be multiply defined, so: 内联函数应该是多重定义的,因此:

#ifdef __cplusplus
extern "C" {
#elif __STDC_VERSION__ >= 199901L
   /* do nothing, C99 supports inline */
#else
#  define inline static
#endif

Many C compilers have non-standard extensions to mark functions as inline, you could also define it as __attribute__((always_inline)) (if __GNUC__ is defined) 许多C编译器都有非标准扩展来将函数标记为内联,您也可以将其定义为__attribute__((always_inline)) (如果定义__GNUC__

EDIT: For better and more complete advice, see: http://www.greenend.org.uk/rjk/2003/03/inline.html 编辑:有关更好和更完整的建议,请参阅: http//www.greenend.org.uk/rjk/2003/03/inline.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM