1.C++的使用场景
#ifdef __cplusplus
extern "C" {
#endif
/*...*/
#ifdef __cplusplus
}
#endif
定义__cplusplus的原因是C语言中不支持extern "C"声明。
2.external的作用
仅仅是声明作用,可以使用外部变量。
一个变量只可以定义1次,但可以声明多次。
3."C"的作用
表示一种编译和连接规约,C和C++的规约是不同的,显示指定"C"可以使用相同的编译方式,在混合编程时很有用。
a.C++分析:
C++编译和连接
void print(int i);
void print(char c);
void print(float f);
void print(char* s);
编译后
_print_int
_print_char
_print_float
_pirnt_string
b.C分析:
C语言中不支持重载和类特性,定义方法,
print(int i);
编译后
_print
c.通过上述证明C++和C编译方式是不兼容的。
4.C++调用C
C文件:
.h
void print(int i);
.c
#include <stdio.h>
#include "cHeader.h"
void print(int i)
{
printf("cHeader %d\n",i);
}
C++文件:
.cpp
extern "C"{
#include "cHeader.h"
}
int main(int argc,char** argv)
{
print(3);
return 0;
}
5.C调用C++
C++文件:
.h:
extern "C" void print(int i);
.cpp:
using namespace std;
void print(int i)
{
cout<<"cppHeader "<<i<<endl;
}
C文件:
extern void print(int i);
int main(int argc,char** argv)
{
print(3);
return 0;
}
6.使用函数指针进行编译和连接
typedef int (*FT) (const void* ,const void*);//style of C++
extern "C"{
typedef int (*CFT) (const void*,const void*);//style of C
}
void isort(void* p,size_t n,size_t sz,FT cmp);//style of C++
void xsort(void* p,size_t n,size_t sz,CFT cmp);//style of C
int compare(const void*,const void*);//style of C++
extern "C" int ccomp(const void*,const void*);//style of C