如何在多个源文件的头文件中包含声明的结构变量?

时间:2022-03-03 15:06:38

I need a struct variable declared and defined in a header file to be accessible from more than one source files but I get a linker error. I'm putting small source code here. Linker error is

我需要在头文件中声明和定义的struct变量,以便可以从多个源文件访问,但是我收到链接器错误。我在这里放小源代码。链接器错误是

main.obj : error LNK2005: _a already defined in library.obj

main.obj:错误LNK2005:_a已在library.obj中定义

fatal error LNK1169: one or more multiply defined symbols found

致命错误LNK1169:找到一个或多个多重定义的符号

header.h

struct Student {
    char *FirstName;
    char *LastName;
};

struct Student a = {"John", "Jackson"};

library.c

#include <stdio.h>
#include "header.h"

void PrintStudentName(struct Student *name)
{
    printf("%s\n%s\n", name->FirstName, name->LastName);
}

main.c

#include <stdio.h>
#include "header.h"


void PrintStudentName(struct Student *name);

int main()
{
    PrintStudentName(&a);
    return 0;
}

2 个解决方案

#1


You should replace this definition line in the header

您应该在标题中替换此定义行

struct Student a = {"John", "Jackson"};

with this declaration:

有这个声明:

extern struct Student a;

This declares a global variable of type struct Student.

这声明了一个struct Student类型的全局变量。

Move the definition into one of the C files to complete the fix:

将定义移动到其中一个C文件中以完成修复:

// This goes into one of the C files, does not matter which one.
struct Student a = {"John", "Jackson"};

#2


Do not have definitions in a header file. These are solely meant to hold the declaration. The definition has to go into an implementation file (*.c). Think of the header file like the interface.

在头文件中没有定义。这些仅用于举行声明。定义必须进入实现文件(* .c)。想想像接口这样的头文件。

Disclaimer: I very well know ther might be exceptions to this rule. Also typedef is actually a definition, but one could just see it as an alias for the actual declaration (this is different from C++, btw).

免责声明:我非常清楚这条规则可能是例外。另外typedef实际上是一个定义,但是人们可以将它看作实际声明的别名(这与C ++,btw不同)。

#1


You should replace this definition line in the header

您应该在标题中替换此定义行

struct Student a = {"John", "Jackson"};

with this declaration:

有这个声明:

extern struct Student a;

This declares a global variable of type struct Student.

这声明了一个struct Student类型的全局变量。

Move the definition into one of the C files to complete the fix:

将定义移动到其中一个C文件中以完成修复:

// This goes into one of the C files, does not matter which one.
struct Student a = {"John", "Jackson"};

#2


Do not have definitions in a header file. These are solely meant to hold the declaration. The definition has to go into an implementation file (*.c). Think of the header file like the interface.

在头文件中没有定义。这些仅用于举行声明。定义必须进入实现文件(* .c)。想想像接口这样的头文件。

Disclaimer: I very well know ther might be exceptions to this rule. Also typedef is actually a definition, but one could just see it as an alias for the actual declaration (this is different from C++, btw).

免责声明:我非常清楚这条规则可能是例外。另外typedef实际上是一个定义,但是人们可以将它看作实际声明的别名(这与C ++,btw不同)。