#ifdef __cplusplus extern "C" { #endif 的解释
在看代码时看到如下的代码:
#ifdef __cplusplus
extern "C" {
#endif
面试时被问到过,不甚明了,网上百度一下,整合了两个仁兄的文章,如下。:-)
时常在cpp的代码之中看到这样的代码:
#ifdef __cplusplus
extern "C" {
#endif
//一段代码
#ifdef __cplusplus
}
#endif
这样的代码到底是什么意思呢?首先,__cplusplus是cpp中的自定义宏,那么定义了这个宏的话表示这是一段cpp的代码,也就是说,上面的代码的含义是:如果这是一段cpp的代码,那么加入extern "C"{和}处理其中的代码。
要明白为何使用extern "C",还得从cpp中对函数的重载处理开始说起。在c++中,为了支持重载机制,在编译生成的汇编码中,要对函数的名字进行一些处理,加入比如函数的返回类型等等.而在C中,只是简单的函数名字而已,不会加入其他的信息.也就是说:C++和C对产生的函数名字的处理是不一样的. 目的就是主要实现C与C++的相互调用问题。
c.h的实现
#ifndef _c_h_
#define _c_h_
#ifdef __cplusplus
extern "C" {
#endif
void C_fun();
#ifdef __cplusplus
}
#endif
#endif
-----------------------------------
c.c的实现
#include "c.h"
void C_fun()
{
}
------------------------------------
在cpp.cpp中调用c.c中的C_test()
cpp.cpp的实现
#include "c.h"
int main()
{
C_fun()
}
其中__cplusplus是C++编译器的保留宏定义.就是说C++编译器认为这个宏已经定义了.
所以关键是extern "C" {}
extern "C"是告诉C++编译器件括号里的东东是按照C的obj文件格式编译的,要连接的话按照C的命名规则去找.
==========================
那么C中是如何调用C++中的函数cpp_fun()呢?
因为先有C后有C++, 所以只能从C++的代码中考虑了.
加入C++中的函数或变量有可能被C中的文件掉用,则应该这样写,也是用extern "C"{}
不过是代码中要加,头文件也要加,因为可能是C++中也调用
--------------------------------------
cpp.h的实现
#ifndef _c_h_
#define _c_h_
#ifdef __cplusplus
extern "C" {
#endif
void CPP_fun();
#ifdef __cplusplus
}
#endif
#endif
.-------------------------------------------
Cpp.cpp的实现
extern "C" { &nbs
相关文档:
FILE* pFile = fopen("1.txt","w");
fwrite("http://www.886997.com",1,strlen(http://www.886997.com),pFile);
fseek(pFile,0,SEEK_SET); //从文件的开始处覆盖写入
char cStr[100];
memset(cStr,0,sizeof(cStr));
fread(cStr,1,100,pFile);
char *pBuf;
fseek(pFile,0,SEEK_END);
int leng = ftell(pFile);
pBuf ......
Linux C + + Training
Syllabus
________________________________________
1, Linux Operating System
System Environment: Ubuntu GNU / Linux, RedHat Linux AS5,
FreeBSD
Course Requirements: proficient use of commonly used Linux
/ UNIX commands.
Time: 1 week.
______________________________ ......
来自:http://zhangjunhd.blog.51cto.com/113473/100299
1.读写字符函数putc()与getc()
这两个函数类似于putchar()与getchar()函数。假设fp是一个FILE指针,ch是一个字符变量,
ch = getc(fp);// ch = getchar();
putc(ch,fp);// putchar(ch);
将文件内容(按字符)输出到标准输出的C实现:
#include <stdio.h ......
前些天,编程序是用到了很久以前写的C程序,想把里面的函数利用起来,连接发现出现了找不到具体函数的错误:
以下是假设旧的C程序库
C的头文件
/*-----------c.h--------------*/
#ifndef _C_H_
#define _C_H_
extern int add(int x, int y);
#endifC的源文件
/*-----------c.c--------------*/
int add(int x, in ......