使用extern变量时出现问题

problem while using extern variable

本文关键字:问题 extern 变量 使用      更新时间:2023-10-16
//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声明与定义中指定的变量类型匹配。

  1. 永远不要声明局部外部变量,根据定义,所有外部变量都是全局的,在本地声明它们会引起混乱
  2. 使用匹配类型extern char *ptr;
  3. 字符串文字是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;
}