解释一下c++中的extern
时间: 2023-07-08 09:19:52 浏览: 54
在C++中,`extern`是一个关键字,可以用来声明一个变量或函数是在其他文件中定义的。它的作用是告诉编译器在本文件中并没有定义该变量或函数,需要在其他文件中查找它的定义。具体来说,`extern`可以有以下两种用法:
1. 声明一个全局变量或函数
```c++
// 在某个头文件中声明全局变量
extern int global_var;
// 在某个头文件中声明函数
extern void func();
```
这样在其他文件中包含该头文件后,就可以使用`global_var`和`func`了。
2. 引用其他文件中的全局变量或函数
```c++
// 在某个头文件中声明全局变量
extern int global_var;
// 在某个源文件中使用该变量
int main() {
// 引用其他文件中定义的全局变量
extern int global_var;
cout << global_var << endl;
return 0;
}
```
这样,在编译时,编译器会在其他文件中查找`global_var`的定义,链接时将其与当前文件中的引用链接起来。
需要注意的是,`extern`只是一个声明,不是定义。定义是在某个文件中初始化变量或函数。如果多个文件中都定义了同名的全局变量或函数,链接时会出现重复定义的错误。
相关问题
c++中extern
extern "C"的作用是用于C和C++混合编程时,告诉编译器某个函数是按照C的链接规则进行编译和链接的。在C++中,函数名会经过名称修饰(name mangling)以支持函数重载,而C语言没有函数重载的概念,因此如果想在C++中调用C语言编写的函数,需要用extern "C"来告诉编译器按照C的链接规则处理该函数。
下面是使用extern "C"的一个例子:
// C代码
#ifdef __cplusplus
extern "C" {
#endif
int add(int a, int b);
#ifdef __cplusplus
}
#endif
// C++代码
#include <iostream>
extern "C" {
#include "mylib.h"
}
int main() {
int result = add(3, 4);
std::cout << "Result: " << result << std::endl;
return 0;
}
c++中externc
在C++中,extern "C"用于声明或定义C语言符号,以便与C兼容。它可以防止C++编译器对函数名进行修饰,从而使得C++代码可以调用C语言编写的函数。下面是一个示例:
```cpp
#ifdef __cplusplus
extern "C" {
#endif
void func(); // 声明一个C语言函数
#ifdef __cplusplus
}
#endif
```
在上面的示例中,我们使用了条件编译来确保只有在C++环境下才会使用extern "C"。这样做是为了避免在C语言环境下出现编译错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)