如何使变量可用于所有包含

How to make a variable available for all inclusions

我有一个头文件,我在其中保留所有全局变量而不分配值,并且我将它包含在主代码中,就像这样。我需要从 Receiver.c 访问 Globals.h 中声明的变量,当我在 Receiver.c 中使用 Globals.h 中的任何变量时,Eclipse 显示未知类型名称

根据编译器,如果我调用 Globals.h 一次,它在编译器内存中对吗?

我没有在 Receiver.c

中包含任何内容
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Globals.h"
#include "my_queue.h"
#include "Receiver.h"
#include "Receiver.c"

这是Globals.h

的内容
int stop_nw_global;
int                   datalen;
int cont[210];
struct in_addr        localInterface;
struct sockaddr_in    groupSock;
int                   sd;
char                  databuf[1024];


typedef struct UDP_Packet {
    unsigned short Year;          // year
    unsigned char  Month;         // months
    unsigned char  Day;           // day
    unsigned char  Hour;          // hour
    unsigned char  Minute;        // minute
    unsigned char  Seconds;       // seconds
    unsigned short Milliseconds;  // milliseconds
    unsigned char  SeqNo;         // packet sequence no
    unsigned short CommandCode;   // packet type
    unsigned char  DestSubSysID;  // Destination sub system id (0 to 255)
    unsigned char  DestNodeID;    // Destination node id
    unsigned char  SrcSubSysID;   // Source sub system id
    unsigned char  SrcNodeID;     // Source node id
    unsigned short DataSize;      // Data size in bytes
    unsigned char  AckSel;        // select acknowledgment option
    unsigned char  AckID;         // ID for ACK
    unsigned char  DataFlag;      // Flag indicating single part(0) or multipart data (1)
    unsigned char  MessageID;     // unique message ID
} UDP_Packet;

但是当我尝试在 receive 和 main 中添加 Globals.h 时,它说,大多数变量的多重定义

src\udpexx1.o:/cygdrive/c/Eclipse Projects/udpexx1/Debug/C:\Eclipse Projects\udpexx1\SocketAPI/Globals.h:3: multiple definition of `stop_nw_global'; SocketAPI\Receiver.o:/cygdrive/c/Eclipse Projects/udpexx1/Debug/C:\Eclipse Projects\udpexx1\SocketAPI/Globals.h:3: first defined here

但两者都指向 Globals.h

使用全局变量几乎总是错误的。在代码中使用全局变量需要一些真正好的论据。所以重新考虑你的设计。

如果您确实需要全局变量,请不要将变量定义放在头文件中。它们属于 C 文件。然后在头文件中做一个外部声明。这样做吧。

somefile.c

int stop_nw_global;  // Define the variable in a c-file

somefile.h

#ifndef SOMEFILE_H   // Include guard
#define SOMEFILE_H

extern int stop_nw_global; // Declare the variable, i.e. tell other c-files
                           // that the variable exists

#endif

otherfile.c

#include somefile.h

...
stop_nw_global = 42;   // Use the variable
...

夜谈otherfile.c

#include somefile.h

...
stop_nw_global = -1;   // Use the variable
...

注意 在头文件中包含 typedef 没问题。这是一个类型定义(不是变量定义)所以没关系