c - 使用 ".h"文件中的结构

标签 c struct header-files extern

假设我有一个包含结构的头文件。

Struct aa 
{
    int a;
    int b;
};

a.c 文件中,我包含该头文件,并且我这样做

struct aa first;

然后使用first.afirst.b进行更改。

b.c 文件中,我包含该头文件,并且我这样做

struct aa first;

然后使用first.afirst.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不会以任何方式影响变量 firstfoo .

如果您想要一个全局变量,以便不同的编译单元(意味着 不同.c文件)如 a.cb.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/

相关文章:

c 扫描文件夹中的新文件

c - 如何忽略 fscanf() 中的空格

C QueueLinkedList 字符串变量不起作用

c - 与c标准头对应的代码在哪里?

c++ - 何时使用 .hpp 文件

c - 为什么我的代码中会出现 __stack_chk_fail?

c - 扫描以 32 个十六进制值表示的 128 位输入

c - 链接列表值指向仅在 C 中更改内部函数

python - Python和C.Bitoperation,.split()函数

c - 符号 "file@variable"定义多次