【发布时间】:2021-08-19 06:34:48
【问题描述】:
我有一个头文件,我在其中保留所有全局变量而不分配值,并将其包含在这样的主代码中。我需要从 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;
但是当我尝试在接收和 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
【问题讨论】:
-
您应该(至少)给出一个错误导致变量声明的示例(在 Globals.h 中)和一个变量使用示例(在 Receiver.c 中)。你给我们的东西很少。
-
如果我调用 Globals.h 一次,它在编译器内存中对吗? 不。首先,你没有“调用”任何东西。
#include是一个预处理器指令。所做的只是替换#include行所在的那个文件的文本。如果你引用了一个编译器在translation unit 中找不到的变量,那么你会得到错误。不确定上面显示的内容,但如果 Receiver.c 需要 Globals.h 中的全局变量,那么 Receiver.c 中的#include "Globals.h"。注意,#include源文件并不常见。 -
@SGeorgiades 我已将 Globals.h 的内容更新为编辑
-
@yano 我正在尝试这样做,但它说多重定义,并且我没有为 .h 文件中的变量分配任何值
-
您应该将header include guards 添加到您的.h 文件中,这可能是您的错误的来源(也请参阅this question)。例如,如果 my_queue.h 和 Receiver.h 都是
#include "Globals.h",那么您有多个stop_mw_global定义(以及 Globals.h 中的所有其他内容)。包括警卫将防止这种情况发生。但是如果没有minimal reproducible example,我认为这里没有足够的信息来给你一个准确的答案。
标签: c linux eclipse header include