1
votes

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

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

fatal error LNK1169: one or more multiply defined symbols found

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

2 Answers

4
votes

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.

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

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

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.

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).