如何在我的程序中的几个文件中共享结构?

lez*_*lon 2 c

这是我的问题:我有一个大的main.c文件,在我的程序中包含40个左右的"全局"结构(它们在文件的开头声明),我在main.c文件中也有几个函数,我能够直接读取和写入这些结构,因为它们是全局的.现在我正在尝试将我原来的main.c文件的几个函数移动到另一个.c文件中,该文件只包含与我程序的特定部分相关的函数.但是我当然不能直接从我的新.c文件中访问main.c全局变量.有没有解决的办法?我想避免通过指针传递每个结构,因为这会得到可怕的函数原型.谢谢

Joe*_*Joe 7

将全局结构定义移动到标头(.h)文件中,并将#include每个c文件中的标头移动到需要访问这些结构的文件中.可以声明任何全局变量extern,然后在main.c中定义.

Global.h

// WARNING: SHARING DATA GLOBALLY IS BAD PRACTICE

#ifndef GLOBAL_H
#define GLOBAL_H

//Any type definitions needed
typedef struct a_struct
{
    int var1;
    long var2;
} a_struct;

//Global data that will be defined in main.c
extern a_struct GlobalStruct;
extern int GlobalCounter;

#endif
Run Code Online (Sandbox Code Playgroud)

main.c中

#include "Global.h"
#include "other.h"

#include <stdio.h>

int GlobalCounter;
a_struct GlobalStruct;

int main(int argc, char *argv[])
{
    GlobalCounter = 5;

    GlobalStruct.var1 = 10;
    GlobalStruct.var2 = 6;

    printf("Counter: %d\nStruct [ var1: %d var2: %ld ]\n", 
           GlobalCounter, GlobalStruct.var1, GlobalStruct.var2);

    do_other_stuff();

    printf("Counter: %d\nStruct [ var1: %d var2: %ld ]\n", 
           GlobalCounter, GlobalStruct.var1, GlobalStruct.var2);

    return 0;   
}
Run Code Online (Sandbox Code Playgroud)

other.h

#ifndef OTHER_H
#define OTHER_H

void do_other_stuff(void);

#endif
Run Code Online (Sandbox Code Playgroud)

other.c

#include "other.h"
#include "Global.h"

void do_other_stuff(void)
{
    GlobalCounter++;
    GlobalStruct.var1 = 100;
    GlobalStruct.var2 = 0xFFFFFF;
}
Run Code Online (Sandbox Code Playgroud)