When to use extern "C"?

I know how to use it extern "C", but what are the conditions when you should use it?

extern "C"tells the C ++ compiler not to do any code name manipulation inside curly braces. This allows you to call C functions from within C ++.

For instance:

#include <string.h>

int main()
{
    char s[] = "Hello";
    char d[6];

    strcpy_s(d, s);
}

While this is compiling on VC ++. But sometimes it is written as:

extern "C" {   
#include <string.h>  
}

I do not see the point. Can you give a real example where extern "C"necessary?

+5
source share
6 answers

You use extern "C"to prevent name manipulation inside the header files and your C ++ object files for libraries or objects that have already been compiled without distortion.

, , widget, C, .

, , , - , .

, - function@intarray_float_charptr, widget function, .

, :

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

, function, .

, C-, C_or ++, , :

#ifdef __cplusplus
    extern "C" {
#endif

// Everything here works for both C and C++ compilers.

#ifdef __cplusplus
    }
#endif

C , #ifdef extern "C". ++ ( __cplusplus) .

+6

extern "C" . ++, , . , , , C-.

+4

, extern "C" .

module.h

int f(int arg);

module.c

int f(int arg) {
  return arg + 1;
}

main.cpp

#include "module.h"

int main() {
  f(42);
}

C ++, ( , f ++ ).

, - C ++:

module.h

#ifdef __cplusplus
  extern "C" {
#endif

int f(int arg);

#ifdef __cplusplus
  }
#endif
+3

, C extern, , . ++ . , . , .

+1
+1

++ #include ( C), extern "C", ( undefined ).

, C , , extern "C" ( #ifdef __cplusplus)

, - ( , Linux) nm, () , .

+1

All Articles