[变量名]的多重声明

Multiple Declarations of [variable name]

我正在编写一个头文件,它为我提供了几个功能。我将头文件包含在两个单独的文件中,即 c 文件和主文件。

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

multiple declarations of ...

错误。

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

根据@Peter的评论进行更正

在 C 中,如果它只包含在一个编译单元中,则只能将变量定义放在 header 中。

你好像有两个编译单元:

  • 编译您的 PLL.h 和 PLL.c 以创建 PLL.o

  • 编译您的 main.c 和 PLL.h 以创建 main.o

你的两个 objects 文件都包含你在 PLL.h 中定义的变量,因此当你点击链接器时它会抛出一个错误,因为变量已经被声明了两次(每个object 文件)。

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

中定义变量

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

extern int x;

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

int x;