[变量名]的多个声明

时间:2019-05-29 12:16:08

标签: c header-files

我正在处理一个为我执行几个功能的头文件。我将头文件包含在两个单独的文件中,即c文件和主文件。

我使用#ifndef#def,但看起来它仍然被编译了两次,因为在链接过程中我得到了服务器化

  

...的多个声明

错误。

PLL头文件

#ifndef PLL_HEADER
#define PLL_HEADER

/********************************************************************
 * includes
 ********************************************************************/
#include "board.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "PITDriver.h"

// Some more stuff

#endif

这是相关的日志数据

[compiling stuff]

Building target: PLL Function.axf
Invoking: MCU Linker

[other linker stuff]

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:45: multiple definition of `accumulateVal'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:45: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:46: multiple definition of `getValOne'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:46: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:47: multiple definition of `getValTwo'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:47: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:48: multiple definition of `countTo'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:48: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:49: multiple definition of `runUntil'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:49: first defined here

./source/main.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:50: multiple definition of `currentValue'
./source/PLL.o:C:\Users\mailn\Desktop\Work\Sparton\MCUXPresso Workstation\PLL Function\Debug/../source/PLL.h:50: first defined here

collect2.exe: error: ld returned 1 exit status
make: *** [makefile:39: PLL Function.axf] Error 1

1 个答案:

答案 0 :(得分:0)

根据@Peter的评论进行纠正

在C语言中,如果变量定义仅包含在一个编译单元中,则只能将其放在标题中。

您似乎有两个编译单元:

  • 一个可以编译PLL.h和PLL.c来创建PLL.o的程序

  • 一个可以编译main.c和PLL.h来创建main.o的文件

这两个目标文件都包含您在PLL.h中定义的变量,因此,当您单击链接器时,它会引发错误,因为变量已被声明两次(每个目标文件中一次)。

要更正此错误,您可以更改合并两个编译单元的编译方式。或者(如果使用自动处理编译的IDE),则可以应用以下更改以避免在标头中定义变量。

在标题中:(将定义更改为声明)

extern int x;

在源文件中:(定义变量)

int x;