How does an extern “C” declaration work?

后端 未结 9 761
礼貌的吻别
礼貌的吻别 2020-12-02 14:33

I\'m taking a programming languages course and we\'re talking about the extern \"C\" declaration.

How does this declaration work at a deeper level othe

9条回答
  •  自闭症患者
    2020-12-02 15:11

    Let's look at a typical function that can compile in both C and C++:

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

    Now in C the function is called "_Add" internally. Whereas the C++ function is called something completely different internally using a system called name-mangling. Its basically a way to name a function so that the same function with different parameters has a different internal name.

    So if Add() is defined in add.c, and you have the prototype in add.h you will get a problem if you try to include add.h in a C++ file. Because the C++ code is looking for a function with a name different to the one in add.c you will get a linker error. To get around that problem you must include add.c by this method:

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

    Now the C++ code will link with _Add instead of the C++ name mangled version.

    That's one of the uses of the expression. Bottom line, if you need to compile code that is strictly C in a C++ program (via an include statement or some other means) you need to wrap it with a extern "C" { ... } declaration.

提交回复
热议问题