我正在为一个头文件执行一些功能。我将头文件包含在两个单独的文件中,即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

最佳答案

根据@Peter的评论进行更正

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

您似乎有两个编译单元:


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


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

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

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

extern int x;


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

int x;

10-06 06:05