使用extern变量时出现问题
problem while using extern variable
//FILE 1
char *ptr="Sample";
void SomeFunction() {
cout<<ptr<<endl;
}
//FILE 2
void SomeFunction();
int main()
{
extern char ptr[];
SomeFunction();
cout<<ptr<<endl;
}
ptr
的主要功能是打印一些垃圾值。请告诉我原因。
ptr
在文件1中声明为指针,在文件2中声明为数组。指针和数组不是一回事,即使它们有时表现得相似。
确保extern
声明与定义中指定的变量类型匹配。
- 永远不要声明局部外部变量,根据定义,所有外部变量都是全局的,在本地声明它们会引起混乱
- 使用匹配类型
extern char *ptr;
- 字符串文字是
const char*
而不是char *
如果您编写了一个与file1.cpp.相对应的头文件,char*
与char[]
的问题可能会被发现
// file1.h
extern char* ptr; // Corresponds to your implementation
// Better:
extern const char * ptr; // Consistent with assignment to a string literal
// Alternative:
extern char ptr[]; // Would require changing implementation in file1 to
// char ptr[] = "Hello world";
您的file2.cpp正在做一些非常糟糕的事情:它正在声明extern
指针本身。永远不要那样做。相反,file2.cpp应该#include
这个新的头文件,就像file1.cpp一样。这样你就会发现不一致,比如你遇到的不一致。
char *
和char []
不是一回事。一个是指针,另一个是数组。请参阅C常见问题解答中的此页。
要么更改File1中的定义,要么更改File2中的声明。
我尽量不忘记一年前学到的一切,所以应该是这样的:
看看Let_Me_Be的回答,获得好的评论。
您的主要函数是打印垃圾,因为您在其中声明的变量与第一个文件中的变量不同。
$ cat print.cpp ;echo ---; cat print2.cpp
#include <stdio.h>
#include <cstdlib>
#include <iostream>
using namespace std;
const char *ptr = "Hello";
void sayLol(){
cout<<ptr<<endl;
}
---
#include <stdio.h>
#include <cstdlib>
#include <iostream>
using namespace std;
void sayLol();
int main(void){
extern char *ptr;
sayLol();
cout<<ptr<<endl;
}
相关文章:
- 警告处理为错误这里有什么问题
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- 最小硬币更换问题(自上而下方法)
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- "Extern"对象问题:错误:Id 返回 1 个退出状态
- extern可以解决这个问题吗,或者我可以通过其他方法解决这个问题吗?
- 具有最小"extern"使用测试用例的未定义引用问题
- c中的Extern关键字问题
- 关于extern和const组合的变量的问题
- 使用extern变量时出现问题