zoukankan      html  css  js  c++  java
  • C++ 为什么要使用#ifdef __cplusplus extern "C" { #endif

    转载: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
    ",Add(6,7));
        printf("Sub=%d
    ",Sub(8,5));
        return 0;
    }
  • 相关阅读:
    什么是tomcat集群?
    cmd黑客入侵命令大全
    Linix基本命令
    Windows CMD命令大全
    python 函数1
    Python 集合(set)使用
    python 数据字典应用
    python 数据运算
    python 数据类型(元组(不可变列表),字符串
    python 数据类型(列表)学习笔记
  • 原文地址:https://www.cnblogs.com/chechen/p/6434456.html
Copyright © 2011-2022 走看看