本例测试在VS2008下extern "C" 对函数名以及函数指针的影响.
//test.h
#ifndef TEST_H
#define TEST_H
#include <iostream>
#define BUFSIZE 1024
#ifdef __cplusplus
extern "C"{
#endif
extern "C" void(*pf2)(void);
void pf3(void (*)(void));
void extern_c_test();
//void extern_c_test(int a);//不能在extern "C"中进行函数重载,这是c所不允许的。
typedef void(* FC)(void);
void pf5(FC);
#ifdef __cplusplus
}
#endif
typedef void(*FCpp)(int);
extern void(*pf)(void);
void pf4(void(*)(void));
void pf5(FC c_func);
void pf6(FCpp cpp_func);
void extern_cpp_test();
void extern_cpp_test(int);
void extern_c_test(int);//这里对extern_c_test进行了重载,这是一个以c++名称修饰规则进行修饰的函数。即是一个c++函数。
#endif
//test.c
#include "gloabal.h"//包含一些库头文件
#include "test.h"
void(*pf)(void);
void (*pf2)(void);
void pf3(void (*)(void)){
printf("This is a C function with a param of a point to a C function.\n");
return;
}
void pf4(void(*)(void)){
using std::cout;
using std::endl;
cout<<"this is a C++ function with a param of a point to a C++ function."<<endl;
return;
}
void pf5(FC c_func){
printf("========Start of pf5(FC c_func)===============\n");
printf("This is a C++ function with a param of a point to a C function.\n");
c_func();
printf("========End of pf5(FC c_func)================\n");
printf("\n");
return;
}
void pf6(FCpp cpp_func){
using std::cout;
using std::endl;
cout<<"\n";
cout<<"========Start of pf6(FC c_func)===============\n";
cout<<"this is a C++ function with a param of a point to a C++ function.\n";
cpp_func(7);
cout<<"========End of pf6(FC c_func)================\n";
cout<<"\n"<<endl;
return;
}
void extern_c_test(){
printf("This is a C function : extern_c_test()\n");
//fn();
return;
}
void extern_c_test(int a){
printf("This is a C function with a int %d for param : extern_c_test(int)\n",a);
return;
}
void extern_cpp_test(){
using std::cout;
using std::endl;
cout<<"This is a C++ function no param : extern_cpp_test()"<<endl;
return;
}
void extern_cpp_test(int a){
using std::cout;
using std::endl;
cout<<"This is a C++ function with a int "<<a<<" for param : extern_cpp_test(int)"<<endl;
return;
}
//main.c
#include "gloabal.h"
#include "test.h"
int main(int argc, char **argv){
using namespace std;
//编译器根据形参模式选择具体的extern_c_test版本:
/*①对于pf5 选择 extern_c_test( );声明为:extern "C" void extern_c_test();是一个用c符号修饰的函数。*/
/*②对于pf6 选择 extern_c_test(int);声明为:void extern_c_test();是一个用c++符号修饰的函数。*/
pf5(extern_c_test);
pf6(extern_c_test);
/*③对于pf5 选择 extern_cpp_test( );声明为:void extern_cpp_test();是一个用c++符号修饰的函数。这里编译能通过。但是对于pf5的声明为:
extern "C" void pf5(FC);
而对于FC的声明为:
extern"C" typedef void( * FC)(void),即将其声明为一个c的函数指针,将一个c++函数名传给pf5,可见,这里编译器只对函数类型进行了检查,并没有对具体怎么修饰函数名进行关注。*/
/*④对于pf6 选择 extern_cpp_test(int);声明为:void extern_cpp_test(int);是一个用c++符号修饰的函数。*/
pf5(extern_cpp_test);
pf6(extern_cpp_test);
return 0;
}