码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 为什么要使用#ifdef __cplusplus extern "C" { #endif

时间:2017-02-23 18:55:45      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:c++   不同   targe   main   函数名   cpp   class   span   fine   

转载:http://www.cnblogs.com/ayanmw/archive/2012/03/15/2398593.html

转载:http://blog.csdn.net/zkl99999/article/details/48134621

转载: http://www.jianshu.com/p/5d2eeeb93590

经常看到别人的头文件 有这样的代码

#ifdef __cplusplus
extern "C" {
#endif

// C 样式 的函数

#ifdef __cplusplus
}
#endif

为什么要这样呢?

因为C语言不支持重载函数,也就是同名函数,参数却不一样,C++支持,其编译器对函数名的处理方法不一样,导致 虽然都是C 样式的函数,不同编译器编译出来的不一样。

如果是C语言编译的中间文件,要C++ 来调用,那么就需要这个了,C++ 有了 extern "C" 就会按照 C 语言的方法进行函数命名。这样编译出来的中间文件就是C样式的函数名,C/C++ 都可以调用。

如果C++ 编译的中间文件,要C语言来调用,是不行的。这也就为什么DLL中常看见extern "C" {},windows是采用C语言编制他首先要考虑到C可以正确调用这些DLL,而用户可能会使用C++而extern "C" {}就会发生作用。

总结:

1.extern "C"表示编译生成的内部符号名使用C约定。

2.C++支持函数重载,而C不支持,两者的编译规则也不一样,函数被C++编译后在符号库中的名字与C语言的不同。

例如,假设某个函数的原型为: void foo( int x, int y ); 该函数被C编译器编译后在符号库中的名字可能为_foo,而C++编译器则会产生像_foo_int_int之类的名字(不同的编译器可能生成的名字不 同,但是都采用了相同的机制,生成的新名字称为“mangled name”)。_foo_int_int这样的名字包含了函数名、函数参数数量及类型信息,C++就是靠这种机制来实现函数重载的。

例子:

test.h

#ifndef _TEST_H_
#define _TEST_H_
#ifdef _cplusplus
extern "c"
{
#endif
    extern int Add(int a, int b);
    extern int Sub(int a, int b);

#ifdef _cplusplus
}
#endif

#endif

test.c

#include "test.h"

int Add(int a, int b)
{
    return a + b;
}

int Sub(int a, int b)
{
    return a - b;
}

main.cpp

#include <stdio.h>

extern "C"
{
#include "test.h"
}

int main()
{
    printf("Add=%d\n",Add(6,7));
    printf("Sub=%d\n",Sub(8,5));
    return 0;
}

 

C++ 为什么要使用#ifdef __cplusplus extern "C" { #endif

标签:c++   不同   targe   main   函数名   cpp   class   span   fine   

原文地址:http://www.cnblogs.com/chechen/p/6434456.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!