假设我有一个包含结构的头文件。
Struct aa
{
int a;
int b;
};
在 a.c
文件中,我包含该头文件,并且我这样做
struct aa first;
然后使用first.a
和first.b
进行更改。
在 b.c
文件中,我包含该头文件,并且我这样做
struct aa first;
然后使用first.a
和first.b
进行更改。
我可以做我在 b.c
中所做的事情吗?联动是如何进行的?它会覆盖这些值吗?它是如何工作的?
或者我应该在任何地方使用 extern 吗?
最佳答案
如果你写struct aa first;
在一个函数中,
// a.c
#include "your_header.h"
void foo(void)
{
struct aa first;
first.a = 18;
first.b = 19;
...
}
// b.c
#include "your_header.h"
void bar(void)
{
struct aa first;
first.a = 21;
first.b = 22;
...
}
那么该变量就是foo
的局部变量和bar
他们分别
碰巧具有相同的名称,但不是相同的变量。所以
first
的初始化在bar
不会以任何方式影响变量
first
在foo
.
如果您想要一个全局变量,以便不同的编译单元(意味着
不同.c
文件)如 a.c
和
b.c
可以访问,那么需要将变量声明为extern
在里面
header 并在 a.c
中定义它或b.c
.
// your_header.h
#ifndef YOURHEADER_H
#define YOURHEADER_H
struct aa {
int a;
int b;
};
// the "extern" tells the compiler that the
// variable might be defined somewhere else,
// it it's not in the current compile unit,
// it won't give you an error.
extern struct first;
#endif
// a.c
#include "your_header.h"
// a.c defines in this compile unit the global
// variable. This information is important for the linker as well
struct first;
void foo(void)
{
first.a = 10;
first.b = 11;
}
//b.c
#include "your_header.h"
void bar(void)
{
first.a = 100;
first.b = 200;
}
现在当你编译a.c
时:gcc a.c -c -o a.o
,编译器从
头文件 first
是一个全局变量,可以在另一个变量中定义
编译单元。在本例中,它在 a.c
中定义。本身。
现在当你编译b.c
时:gcc b.c -c -o b.o
,编译器从
头文件 first
是一个全局变量,可以在另一个变量中定义
编译单元。它没有在 b.c
中定义。 ,所以编译器会让链接器
处理这个。
当您链接程序时:gcc a.o b.o othermodules.o -o myprogram
, 这
链接器将知道变量 first
在哪个目标文件中被定义并将
为程序访问此变量时创建正确的偏移量。
在这种情况下,如果您在 main
中执行此操作.
#include "your_header.h"
#include "other_headers.h"
int main(void)
{
foo();
bar();
}
然后bar
将覆盖 first.a
的值和first.b
设置于 foo
,
因为first
是一个全局变量。
关于c - 使用 ".h"文件中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48877017/