97
extern "C" void foo(int); extern "C" { void g(char); int i; }
89
#ifdef __cplusplus extern "C" { #endif // all of your legacy C code here #ifdef __cplusplus } #endif
extern "C" { #include "legacy_C_header.h" }
72
void f() {} void g(); extern "C" { void ef() {} void eg(); } /* Prevent g and eg from being optimized away. */ void h() { g(); eg(); }
g++ -c -std=c++11 -Wall -Wextra -pedantic -o main.o main.cpp readelf -s main.o
8: 0000000000000000 7 FUNC GLOBAL DEFAULT 1 _Z1fv 9: 0000000000000007 7 FUNC GLOBAL DEFAULT 1 ef 10: 000000000000000e 17 FUNC GLOBAL DEFAULT 1 _Z1hv 11: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _GLOBAL_OFFSET_TABLE_ 12: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _Z1gv 13: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND eg
$ c++filt _Z1fv f() $ c++filt _Z1hv h() $ c++filt _Z1gv g()
extern "C" { // Overloading. // error: declaration of C function ‘void f(int)’ conflicts with void f(); void f(int i); // Templates. // error: template with C linkage template <class C> void f(C i) { } }
#include <cassert> #include "c.h" int main() { assert(f() == 1); }
#ifndef C_H #define C_H /* This ifdef allows the header to be used from both C and C++ * because C does not know what this extern "C" thing is. */ #ifdef __cplusplus extern "C" { #endif int f(); #ifdef __cplusplus } #endif #endif
#include "c.h" int f(void) { return 1; }
g++ -c -o main.o -std=c++98 main.cpp gcc -c -o c.o -std=c89 c.c g++ -o main.out main.o c.o ./main.out
main.cpp:6: undefined reference to `f()'
#include <assert.h> #include "cpp.h" int main(void) { assert(f_int(1) == 2); assert(f_float(1.0) == 3); return 0; }
#ifndef CPP_H #define CPP_H #ifdef __cplusplus // C cannot see these overloaded prototypes, or else it would get confused. int f(int i); int f(float i); extern "C" { #endif int f_int(int i); int f_float(float i); #ifdef __cplusplus } #endif #endif
#include "cpp.h" int f(int i) { return i + 1; } int f(float i) { return i + 2; } int f_int(int i) { return f(i); } int f_float(float i) { return f(i); }
gcc -c -o main.o -std=c89 -Wextra main.c g++ -c -o cpp.o -std=c++98 cpp.cpp g++ -o main.out main.o cpp.o ./main.out
main.c:6: undefined reference to `f_int' main.c:7: undefined reference to `f_float'
60
#include <stdio.h> // Two functions are defined with the same name // but have different parameters void printMe(int a) { printf("int: %i\n", a); } void printMe(char a) { printf("char: %c\n", a); } int main() { printMe('a'); printMe(1); return 0; }