简体   繁体   中英

linux gcc linker problems with C program

I am trying to compile ac 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");
}

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

将extern设置为xxx并在.c文件中定义xxx。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM