tags:

views:

58

answers:

3

I am trying to compile a c program that includes a header in to .c files. but only 1 of the .c files is really using the defined variable in the header file. here is some sample code that will generate the linker problem. I am trying to have my header file contain global variables that are used by 2 different .c files... Any kind of help would be appreciated. thanks.

tmp1.h file

#ifndef TMP1_H_1
#define TMP1_H_1

double xxx[3] = {1.0,2.0,3.0};

#endif

tmp1.c file

#include "tmp1.h"

void testing()
{
  int x = 0;
  x++;
  xxx[1] = 8.0;
}

main1.c file

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

int main()
{
 printf("hello world\n");
}
+5  A: 

The problem is you're initializing a variable in a header file, so you're getting duplicate symbols. You need to declare double xxx with the extern keyword, and then initialize it in either .c file.

Like so:

#ifndef TMP1_H_1
#define TMP1_H_1

extern double xxx[3];

#endif

And then in one of the .c files:

double xxx[3] = {1.0,2.0,3.0};
Charles Salvia
+1, but I'd like to point out that there's no need for the extern at all if "only 1 of the .c files is really using the defined variable" - just declare, define and use it in that c file.
paxdiablo
True. In fact, assuming the OP's actual code isn't any more complicated than what has been posted, there's no need for the second .c file to even include the header file at all.
Charles Salvia
+1  A: 

Don't put code in header files, it's a recipe for "multiply-defined symbol" linker errors. Put an extern reference to your global variable in the header file, and then define the actual global in one of your C files (or even a new one).

Carl Norum
A: 

put extern for xxx and define xxx in a .c file.

Murali VP