面试题答案
一键面试设计思路
- 在C++ 中,
extern "C"
用于指定函数采用C语言的链接约定,这样C++ 代码在调用C函数时,编译器不会对函数名进行重整(name mangling),从而确保链接时能找到正确的函数实现。 - 对于跨C和C++ 的项目,需要一种机制来判断当前编译环境是C还是C++。在C++ 中,预定义宏
__cplusplus
会被定义,而在C中则不会。 - 根据
__cplusplus
的定义与否,对函数声明进行不同处理。如果是C++ 环境,使用extern "C"
包裹函数声明;如果是C环境,则直接声明函数。
具体实现代码
// common.h
#ifndef COMMON_H
#define COMMON_H
#ifdef __cplusplus
extern "C" {
#endif
// 函数声明
void cFunction();
void cppFunction();
#ifdef __cplusplus
}
#endif
#endif // COMMON_H
在C代码中包含 common.h
时,由于没有定义 __cplusplus
,函数声明就如同普通C语言头文件一样。在C++ 代码中包含 common.h
时,__cplusplus
被定义,函数声明会被 extern "C"
包裹,确保C++ 代码以C语言链接约定来处理这些函数。
在C实现文件(例如 c_file.c
)中:
#include "common.h"
#include <stdio.h>
void cFunction() {
printf("This is a C function.\n");
}
在C++ 实现文件(例如 cpp_file.cpp
)中:
#include "common.h"
#include <iostream>
void cppFunction() {
std::cout << "This is a C++ function." << std::endl;
}