Question

Why does MSVS refuse to compile the following?

config.h

char *names[][2] = { 
    { "Marry", "McBlith" }, 
    { "Nadja", "Nurales"}
};   

main.c

#include <Windows.h>
#include <stdio.h>
#include "config.h"

int main()
{
   printf("TEST (names[0][0]): %s\n", names[0][0]);

   return 0;
}

Output:

1>c:\projects\test\config.h(2): error C2374: 'names' : redefinition; multiple initialization
1>c:\projects\test\config.h(2) : see declaration of 'names'

Error List:

Error 1 error C2374: 'names' : redefinition; multiple initialization c:\projects\test\config.h 2 1 test

Why does MSVS 2013 tell me its a multiple initialization when the array names[][2] is only declared and initialized once in config.h?

What am I doing wrong and what do I have to change to get this working?

Greetings

Was it helpful?

Solution

Don't put definitions in header files, then you will have those definition in all translation units that include the header file.

Instead have only a declaration in the header file:

extern char *names[][2];

And then put the definition in one source file.

Also, you might want to have include guards in your header file, to protect it from being included twice in a single source file.

OTHER TIPS

in an IDE like VisualStudio you have the optional addition to say, which header files to use, without #include'ing them (in gcc, that would be an optional parameter to the call), so may be including the header file twice.

this is normally ignored by including

#ifndef __CONFIG_H__ 
#define __CONFIG_H__
#endif

but normally you never define anything in a headerfile, just decalre things

Yes I'm including this file in another sourcefile. I'll try putting it in the code file though.

This is what you are doing mistake with out having Header guards. You are including many times.

Use Header Guards.
And in your source files declare using extern

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top