<p>Why do we need to use:</p>

<pre><code>extern "C" {
#include &lt;foo.h&gt;
}
</code></pre>

<p><strong>Specifically:</strong>  </p>

<ul>
<li><p>When should we use it?</p></li>
<li><p>What is happening at the compiler/linker level that requires us to use it?  </p></li>
<li><p>How in terms of compilation/linking does this solve the problems which require us to use it?</p></li>
</ul>

[{'answer_id': 67919, 'author': '1800 INFORMATION', 'author_id': 3146, 'author_profile': 'https://Stackoverflow.com/users/3146', 'pm_score': 4, 'selected': False, 'text': '<p>It has to do with the way the different compilers perform name-mangling. A C++ compiler will mangle the name of a symbol exported from the header file in a completely different way than a C compiler would, so when you try to link, you would get a linker error saying there were missing symbols.</p>\n\n<p>To resolve this, we tell the C++ compiler to run in "C" mode, so it performs name mangling in the same way the C compiler would. Having done so, the linker errors are fixed.</p>\n'}, {'answer_id': 67922, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 3, 'selected': False, 'text': '<p>This is used to resolve name mangling issues.  extern C means that the functions are in a "flat" C-style API.</p>\n'}, {'answer_id': 67923, 'author': 'mbyrne215', 'author_id': 5241, 'author_profile': 'https://Stackoverflow.com/users/5241', 'pm_score': 3, 'selected': False, 'text': '<p>The C++ compiler creates symbol names differently than the C compiler.  So, if you are trying to make a call to a function that resides in a C file, compiled as C code, you need to tell the C++ compiler that the symbol names that it is trying to resolve look different than it defaults to; otherwise the link step will fail.</p>\n'}, {'answer_id': 67930, 'author': 'gnkdl_gansklgna', 'author_id': 10470, 'author_profile': 'https://Stackoverflow.com/users/10470', 'pm_score': 8, 'selected': True, 'text': "<p>C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI', or 'Application Binary Interface', so the linker chokes up. This is preferable to passing C++ data to a function expecting C data.</p>\n<p>(To get into the really nitty-gritty, C++'s ABI generally 'mangles' the names of their functions/methods, so calling <code>printf()</code> without flagging the prototype as a C function, the C++ will actually generate code calling <code>_Zprintf</code>, plus extra crap at the end.)</p>\n<p>So: use <code>extern &quot;C&quot; {...}</code> when including a c header—it's that simple. Otherwise, you'll have a mismatch in compiled code, and the linker will choke. For most headers, however, you won't even need the <code>extern</code> because most system C headers will already account for the fact that they might be included by C++ code and already <code>extern &quot;C&quot;</code> their code.</p>\n"}, {'answer_id': 67932, 'author': 'Trent', 'author_id': 9083, 'author_profile': 'https://Stackoverflow.com/users/9083', 'pm_score': 5, 'selected': False, 'text': '<p>In C++, you can have different entities that share a name.  For example here is a list of functions all named <em>foo</em>: </p>\n\n<ul>\n<li><code>A::foo()</code></li>\n<li><code>B::foo()</code></li>\n<li><code>C::foo(int)</code></li>\n<li><code>C::foo(std::string)</code></li>\n</ul>\n\n<p>In order to differentiate between them all, the C++ compiler will create unique names for each in a process called name-mangling or decorating.  C compilers do not do this.  Furthermore, each C++ compiler may do this is a different way.</p>\n\n<p>extern "C" tells the C++ compiler not to perform any name-mangling on the code within the braces.  This allows you to call C functions from within C++.</p>\n'}, {'answer_id': 67936, 'author': 'tialaramex', 'author_id': 9654, 'author_profile': 'https://Stackoverflow.com/users/9654', 'pm_score': 4, 'selected': False, 'text': '<p>C and C++ have different rules about names of symbols. Symbols are how the linker knows that the call to function "openBankAccount" in one object file produced by the compiler is a reference to that function you called "openBankAccount" in another object file produced from a different source file by the same (or compatible) compiler. This allows you to make a program out of more than one source file, which is a relief when working on a large project.</p>\n\n<p>In C the rule is very simple, symbols are all in a single name space anyway. So the integer "socks" is stored as "socks" and the function count_socks is stored as "count_socks".</p>\n\n<p>Linkers were built for C and other languages like C with this simple symbol naming rule. So symbols in the linker are just simple strings.</p>\n\n<p>But in C++ the language lets you have namespaces, and polymorphism and various other things that conflict with such a simple rule. All six of your polymorphic functions called "add" need to have different symbols, or the wrong one will be used by other object files. This is done by "mangling" (that\'s a technical term) the names of symbols.</p>\n\n<p>When linking C++ code to C libraries or code, you need extern "C" anything written in C, such as header files for the C libraries, to tell your C++ compiler that these symbol names aren\'t to be mangled, while the rest of your C++ code of course must be mangled or it won\'t work.</p>\n'}, {'answer_id': 67938, 'author': 'Tony M', 'author_id': 10494, 'author_profile': 'https://Stackoverflow.com/users/10494', 'pm_score': 4, 'selected': False, 'text': "<blockquote>\n  <p>When should we use it?</p>\n</blockquote>\n\n<p>When you are linking C libaries into C++ object files</p>\n\n<blockquote>\n  <p>What is happening at the\n  compiler/linker level that requires us\n  to use it?</p>\n</blockquote>\n\n<p>C and C++ use different schemes for symbol naming.  This tells the linker to use C's scheme when linking in the given library.</p>\n\n<blockquote>\n  <p>How in terms of compilation/linking\n  does this solve the problems which\n  require us to use it?</p>\n</blockquote>\n\n<p>Using the C naming scheme allows you to reference C-style symbols. Otherwise the linker would try C++-style symbols which wouldn't work.</p>\n"}, {'answer_id': 67942, 'author': 'Paul Lalonde', 'author_id': 5782, 'author_profile': 'https://Stackoverflow.com/users/5782', 'pm_score': 3, 'selected': False, 'text': '<p>The <code>extern "C" {}</code> construct instructs the compiler not to perform mangling on names declared within the braces. Normally, the C++ compiler "enhances" function names so that they encode type information about arguments and the return value; this is called the <em>mangled name</em>. The <code>extern "C"</code> construct prevents the mangling.</p>\n\n<p>It is typically used when C++ code needs to call a C-language library. It may also be used when exposing a C++ function (from a DLL, for example) to C clients.</p>\n'}, {'answer_id': 67985, 'author': 'Todd Gamblin', 'author_id': 9122, 'author_profile': 'https://Stackoverflow.com/users/9122', 'pm_score': 7, 'selected': False, 'text': '<p>extern "C" determines how symbols in the generated object file should be named.  If a function is declared without extern "C", the symbol name in the object file will use C++ name mangling.  Here\'s an example.</p>\n\n<p>Given test.C like so:</p>\n\n<pre><code>void foo() { }\n</code></pre>\n\n<p>Compiling and listing symbols in the object file gives:</p>\n\n<pre><code>$ g++ -c test.C\n$ nm test.o\n0000000000000000 T _Z3foov\n                 U __gxx_personality_v0\n</code></pre>\n\n<p>The foo function is actually called "_Z3foov".  This string contains type information for the return type and parameters, among other things.  If you instead write test.C like this:</p>\n\n<pre><code>extern "C" {\n    void foo() { }\n}\n</code></pre>\n\n<p>Then compile and look at symbols:</p>\n\n<pre><code>$ g++ -c test.C\n$ nm test.o\n                 U __gxx_personality_v0\n0000000000000000 T foo\n</code></pre>\n\n<p>You get C linkage.  The name of the "foo" function in the object file is just "foo", and it doesn\'t have all the fancy type info that comes from name mangling.</p>\n\n<p>You generally include a header within extern "C" {} if the code that goes with it was compiled with a C compiler but you\'re trying to call it from C++.  When you do this, you\'re telling the compiler that all the declarations in the header will use C linkage.  When you link your code, your .o files will contain references to "foo", not "_Z3fooblah", which hopefully matches whatever is in the library you\'re linking against.</p>\n\n<p>Most modern libraries will put guards around such headers so that symbols are declared with the right linkage.  e.g. in a lot of the standard headers you\'ll find:</p>\n\n<pre><code>#ifdef __cplusplus\nextern "C" {\n#endif\n\n... declarations ...\n\n#ifdef __cplusplus\n}\n#endif\n</code></pre>\n\n<p>This makes sure that when C++ code includes the header, the symbols in your object file match what\'s in the C library.  You should only have to put extern "C" {} around your C header if it\'s old and doesn\'t have these guards already.</p>\n'}, {'answer_id': 67987, 'author': 'HitScan', 'author_id': 9490, 'author_profile': 'https://Stackoverflow.com/users/9490', 'pm_score': 3, 'selected': False, 'text': '<p>You should use extern "C" anytime that you include a header defining functions residing in a file compiled by a C compiler, used in a C++ file. (Many standard C libraries may include this check in their headers to make it simpler for the developer)</p>\n\n<p>For example, if you have a project with 3 files, util.c, util.h, and main.cpp and both the .c and .cpp files are compiled with the C++ compiler (g++, cc, etc) then it isn\'t really needed, and may even cause linker errors. If your build process uses a regular C compiler for util.c, then you will need to use extern "C" when including util.h.</p>\n\n<p>What is happening is that C++ encodes the parameters of the function in its name. This is how function overloading works. All that tends to happen to a C function is the addition of an underscore ("_") to the beginning of the name. Without using extern "C" the linker will be looking for a function named DoSomething@@int@float() when the function\'s actual name is _DoSomething() or just DoSomething().</p>\n\n<p>Using extern "C" solves the above problem by telling the C++ compiler that it should look for a function that follows the C naming convention instead of the C++ one.</p>\n'}, {'answer_id': 56136918, 'author': 'Ciro Santilli OurBigBook.com', 'author_id': 895245, 'author_profile': 'https://Stackoverflow.com/users/895245', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Decompile a <code>g++</code> generated binary to see what is going on</strong></p>\n\n<p>To understand why <code>extern</code> is necessary, the best thing to do is to understand what is going on in detail in the object files with an example:</p>\n\n<p>main.cpp</p>\n\n<pre><code>void f() {}\nvoid g();\n\nextern "C" {\n    void ef() {}\n    void eg();\n}\n\n/* Prevent g and eg from being optimized away. */\nvoid h() { g(); eg(); }\n</code></pre>\n\n<p>Compile with GCC 4.8 Linux <a href="https://stackoverflow.com/questions/26294034/how-to-make-an-executable-elf-file-in-linux-using-a-hex-editor/30648229#30648229">ELF</a> output:</p>\n\n<pre><code>g++ -c main.cpp\n</code></pre>\n\n<p>Decompile the symbol table:</p>\n\n<pre><code>readelf -s main.o\n</code></pre>\n\n<p>The output contains:</p>\n\n<pre><code>Num:    Value          Size Type    Bind   Vis      Ndx Name\n  8: 0000000000000000     6 FUNC    GLOBAL DEFAULT    1 _Z1fv\n  9: 0000000000000006     6 FUNC    GLOBAL DEFAULT    1 ef\n 10: 000000000000000c    16 FUNC    GLOBAL DEFAULT    1 _Z1hv\n 11: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _Z1gv\n 12: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND eg\n</code></pre>\n\n<p><strong>Interpretation</strong></p>\n\n<p>We see that:</p>\n\n<ul>\n<li><p><code>ef</code> and <code>eg</code> were stored in symbols with the same name as in the code</p></li>\n<li><p>the other symbols were mangled. Let\'s unmangle them:</p>\n\n<pre><code>$ c++filt _Z1fv\nf()\n$ c++filt _Z1hv\nh()\n$ c++filt _Z1gv\ng()\n</code></pre></li>\n</ul>\n\n<p>Conclusion: both of the following symbol types were <em>not</em> mangled:</p>\n\n<ul>\n<li>defined</li>\n<li>declared but undefined (<code>Ndx = UND</code>), to be provided at link or run time from another object file</li>\n</ul>\n\n<p>So you will need <code>extern "C"</code> both when calling:</p>\n\n<ul>\n<li>C from C++: tell <code>g++</code> to expect unmangled symbols produced by <code>gcc</code></li>\n<li>C++ from C: tell <code>g++</code> to generate unmangled symbols for <code>gcc</code> to use</li>\n</ul>\n\n<p><strong>Things that do not work in extern C</strong></p>\n\n<p>It becomes obvious that any C++ feature that requires name mangling will not work inside <code>extern C</code>:</p>\n\n<pre><code>extern "C" {\n    // Overloading.\n    // error: declaration of C function ‘void f(int)’ conflicts with\n    void f();\n    void f(int i);\n\n    // Templates.\n    // error: template with C linkage\n    template &lt;class C&gt; void f(C i) { }\n}\n</code></pre>\n\n<p><strong>Minimal runnable C from C++ example</strong></p>\n\n<p>For the sake of completeness and for the newbs out there, see also: <a href="https://stackoverflow.com/questions/13694605/how-to-use-c-source-files-in-a-c-project/51912672#51912672">How to use C source files in a C++ project?</a></p>\n\n<p>Calling C from C++ is pretty easy: each C function only has one possible non-mangled symbol, so no extra work is required.</p>\n\n<p>main.cpp</p>\n\n<pre><code>#include &lt;cassert&gt;\n\n#include "c.h"\n\nint main() {\n    assert(f() == 1);\n}\n</code></pre>\n\n<p>c.h</p>\n\n<pre><code>#ifndef C_H\n#define C_H\n\n/* This ifdef allows the header to be used from both C and C++. */\n#ifdef __cplusplus\nextern "C" {\n#endif\nint f();\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n</code></pre>\n\n<p>c.c</p>\n\n<pre><code>#include "c.h"\n\nint f(void) { return 1; }\n</code></pre>\n\n<p>Run:</p>\n\n<pre><code>g++ -c -o main.o -std=c++98 main.cpp\ngcc -c -o c.o -std=c89 c.c\ng++ -o main.out main.o c.o\n./main.out\n</code></pre>\n\n<p>Without <code>extern "C"</code> the link fails with:</p>\n\n<pre><code>main.cpp:6: undefined reference to `f()\'\n</code></pre>\n\n<p>because <code>g++</code> expects to find a mangled <code>f</code>, which <code>gcc</code> did not produce.</p>\n\n<p><a href="https://github.com/cirosantilli/cpp-cheat/tree/bf5f48628d0b01ba6a3fcea6f1162b28539654c9/c-from-cpp" rel="nofollow noreferrer">Example on GitHub</a>.</p>\n\n<p><strong>Minimal runnable C++ from C example</strong></p>\n\n<p>Calling C++ from is a bit harder: we have to manually create non-mangled versions of each function we want to expose.</p>\n\n<p>Here we illustrate how to expose C++ function overloads to C.</p>\n\n<p>main.c</p>\n\n<pre><code>#include &lt;assert.h&gt;\n\n#include "cpp.h"\n\nint main(void) {\n    assert(f_int(1) == 2);\n    assert(f_float(1.0) == 3);\n    return 0;\n}\n</code></pre>\n\n<p>cpp.h</p>\n\n<pre><code>#ifndef CPP_H\n#define CPP_H\n\n#ifdef __cplusplus\n// C cannot see these overloaded prototypes, or else it would get confused.\nint f(int i);\nint f(float i);\nextern "C" {\n#endif\nint f_int(int i);\nint f_float(float i);\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n</code></pre>\n\n<p>cpp.cpp</p>\n\n<pre><code>#include "cpp.h"\n\nint f(int i) {\n    return i + 1;\n}\n\nint f(float i) {\n    return i + 2;\n}\n\nint f_int(int i) {\n    return f(i);\n}\n\nint f_float(float i) {\n    return f(i);\n}\n</code></pre>\n\n<p>Run:</p>\n\n<pre><code>gcc -c -o main.o -std=c89 -Wextra main.c\ng++ -c -o cpp.o -std=c++98 cpp.cpp\ng++ -o main.out main.o cpp.o\n./main.out\n</code></pre>\n\n<p>Without <code>extern "C"</code> it fails with:</p>\n\n<pre><code>main.c:6: undefined reference to `f_int\'\nmain.c:7: undefined reference to `f_float\'\n</code></pre>\n\n<p>because <code>g++</code> generated mangled symbols which <code>gcc</code> cannot find.</p>\n\n<p><a href="https://github.com/cirosantilli/cpp-cheat/tree/bf5f48628d0b01ba6a3fcea6f1162b28539654c9/cpp-from-c" rel="nofollow noreferrer">Example on GitHub</a>.</p>\n\n<p>Tested in Ubuntu 18.04.</p>\n'}]
['https://Stackoverflow.com/questions/67894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1597/']