如何从另一个C文件中访问变量?

我有两个C文件。 我想在一个中声明一个变量,然后能够从另一个C文件访问它。 我对示例字符串的定义可能并不完美,但您明白了。

//file1.c char *hello="hello"; 

 //file2.c printf("%s",hello); 

 // file1.h #ifndef FILE1_H #define FILE1_H extern char* hello; #endif // file1.c // as before // file2.c #include "file1.h" // the rest as before 

*hello file1.c *hello必须声明为global ,而file2.c extern必须是全局的 (不在函数内

 //file2.c extern char *hello; ... function() { printf(...) } 

你有什么工作。 您想要研究的是C中的“链接”。基本上不在函数内或标记为静态的对象是extern(想想全局)。 在这种情况下,您需要做的是通知编译器实际上有一个名为hello的变量在别处定义。 您可以通过将以下行添加到file2.c来完成此操作

 extern char* hello; 

这很有效

TC

 #include  int main(void) { extern int d; printf("%d" "\n", d); return 0; } 

HC

 int d = 1; 

产量

 [guest@localhost tests]$ .ansi tc hc -ot [guest@localhost tests]$ ./t 1 [guest@localhost ~]$ alias .ansi alias .ansi='cc -ansi -pedantic -Wall' [guest@localhost ~]$ 

在file1.c

 int temp1=25; int main() { . . } 

file2.c中

  extern int temp1; func1(); func2(temp1); 

temp1file1.c中定义。如果要在file2.c使用它,则必须编写extern int temp1 ; 您必须在要使用此变量的每个文件中执行此操作

file_2.c

 #include int count; void extern_function(); void main() { count = 5; extern_function(); } 

file_3.c

 #include void extern_function() { extern int count; printf("the value from the external file is %d",count); } 

现在运行代码

  $gcc file_2.c file_3.c -o test $./test 

有用!!