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 s开发者_JAVA技巧ome 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");
}
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};
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).
put extern for xxx and define xxx in a .c file.
精彩评论