简体   繁体   English

linux gcc链接器问题与C程序

[英]linux gcc linker problems with C program

I am trying to compile ac program that includes a header in to .c files. 我正在尝试编译包含.c文件头的ac程序。 but only 1 of the .c files is really using the defined variable in the header file. 但是.c文件中只有1个确实在使用头文件中的已定义变量。 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. 我正在尝试让我的头文件包含由2个不同的.c文件使用的全局变量...任何帮助将不胜感激。 thanks. 谢谢。

tmp1.h file tmp1.h文件

#ifndef TMP1_H_1
#define TMP1_H_1

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

#endif

tmp1.c file tmp1.c文件

#include "tmp1.h"

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

main1.c file main1.c文件

#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. 您需要使用extern关键字声明double xxx ,然后在任一.c文件中对其进行初始化。

Like so: 像这样:

#ifndef TMP1_H_1
#define TMP1_H_1

extern double xxx[3];

#endif

And then in one of the .c files: 然后在一个.c文件中:

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引用,然后在一个C文件(甚至一个新文件)中定义实际的全局变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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