extern "C"

 
 
First of all, __cplusplus is a custom macro in cpp. If you define this macro, it means that this is a piece of cpp code. 

Take a common code in cpp programs:
#ifdef __cplusplus
extern "C " {
#endif
…………
…………
#ifdef __cplusplus
}
#endif

The meaning of the above code: if the compiler is compiling the cpp file, then __cplusplus The macro will be defined; if a c file is being compiled then the __STDC__ macro will be defined.
If the whole program is written in C++, the extern "C " {} should be added to write C in C++. As for extern "C" this instructs the compiler to generate the symbol table without changing the name of the identifier.
experiment:
test.h
#ifndef __TEST_H__
#define __TEST_H__

#ifdef __cplusplus
#include <iostream>
using namespace std;
extern "C"
{
#endif

void mytest();

#ifdef __cplusplus	
}
#endif

#endif

test.c/test.cpp

#include "test.h"
 void mytest()
 {
 	#ifdef __cplusplus
 	cout << "cout mytest extern ok" << endl;
 	#else
 	printf("printf mytest extern ok");
 	#endif
 }
main.c
#include <iostream.h>
#include "test.h"
int main(int argc, char *argv[])
{
	//cout<<"Hello C-Free!"<<endl;
	mytest();
	return 0;
}

When the test source file is: test.cpp, the test result is:

cout mytest extern ok

When the test source file is: test.c, the test result is:

printf mytest extern ok


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326009616&siteId=291194637