• [C/CPP系列知识] C++中extern “C” name mangling -- Name Mangling and extern “C” in C++


    http://www.geeksforgeeks.org/extern-c-in-c/

    C++函数重载(function overloading),但是C++编译器是如何区分不同的函数的呢?----是通过在函数名是加些信息来区不同的函数,即所谓的Name Mangling。C++标准并没有对name mangling技术,各个编译器可以添加不同的信息。

    考虑下面的函数

    int  f (void) { return 1; }
    int  f (int)  { return 0; }
    void g (void) { int i = f(), j = f(0); }

    C++编译器也许会重命名为 (Source: Wiki)

    int  __f_v (void) { return 1; }
    int  __f_i (int)  { return 0; }
    void __g_v (void) { int i = __f_v(), j = __f_i(0); }

    C++链接器如何处理C语言中的符号呢?

    C语言不支持函数重载,所以没有name mangling技术,那么在C++中使用了C函数后如何保证C++链接器能够正取的链接呢?

    // Save file as .cpp and use C++ compiler to compile it
    int printf(const char *format,...);
     
    int main()
    {
        printf("GeeksforGeeks");
        return 0;
    }

    编译结果:

    diego@ubuntu:~/myProg/geeks4geeks/cpp$ g++ test11.cpp 
    test11.cpp:1:2: error: invalid preprocessing directive #int
     #int printf(const char *format,...);
      ^
    test11.cpp: In function 'int main()':
    test11.cpp:5:29: error: 'printf' was not declared in this scope
         printf("GeeksforGeeks
    ");
                                 ^
    diego@ubuntu:~/myProg/geeks4geeks/cpp$

    编译错误的原因是C++编译器对printf函数进行了name mangling,然后找不到重命名后的函数的符号。解决办法就是使用extern "C" 关键字。

    // Save file as .cpp and use C++ compiler to compile it
    extern "C"
    {
        int printf(const char *format,...);
    }
     
    int main()
    {
        printf("GeeksforGeeks");
        return 0;
    }

    输出结果:

    diego@ubuntu:~/myProg/geeks4geeks/cpp$ g++ test11.cpp 
    diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 
    GeeksforGeeks

    所以,所有的C语言的库函数都要包含在extern “C” block中。

    #ifdef __cplusplus 
    extern "C" {
    #endif
        /* Declarations of this file */
    #ifdef __cplusplus
    }
    #endif
  • 相关阅读:
    匿名函数
    内置函数
    基础函数--3
    基础函数(2)
    基础函数(1)
    文件的相关操作
    知识点补充,set集合,深浅copy
    is 和 ==的区别
    Django-form组件中过滤当前用户信息
    Django的常用模块引入整理
  • 原文地址:https://www.cnblogs.com/diegodu/p/4581888.html
Copyright © 2020-2023  润新知