簡體   English   中英

Arduino庫:函數的多個定義

[英]Arduino library: multiple definitions of a function

今天我在嘗試使用IRremote庫時遇到了一個奇怪的問題,我設法解決了以下問題。 如果你在庫中有一個文件夾,里面有Foo.hFoo.cpp ,並寫一個草圖來包含Foo.h:

foo.h中

#ifndef Foo_H
#define Foo_H

int AAA() {
    return 0;
}

#endif

Foo.cpp中

#include "Foo.h"

草圖

#include <Foo.h>

void setup(){

}

void loop(){

}

錯誤消息是:

 Foo\Foo.cpp.o: In function `AAA()':

 E:\workShop\Arduino\libraries\Foo\/Foo.h:5: multiple definition of `AAA()'

 includeTest.cpp.o:E:\workShop\Arduino\libraries\Foo/Foo.h:5:

 first defined here

我正在使用Windows 7 32位機器。 在Arduino 1.0.5,1.0.4和21,22上測試。


因此,通過一些研究,我發現問題來自於我對預處理器和鏈接的混淆。 這個問題解釋了預處理器如何包含文件和包含防護:

以下是幫助我理解鏈接的一些頁面:

這是對內聯說明符的更好解釋:

好吧,你已經在兩個地方定義了這個函數:一次在Foo.cpp中,它包含標題,再次在你的草圖中包含標題。 C和C ++頭文件不提供模塊系統,它們只是字面上粘貼代替include語句。

在標題中聲明 AAA ,但在Foo.cpp中定義它(因此只有一個定義),或者將其標記為inline

好吧,至少可以說,你文件中的東西分布是不尋常的。

以下是通常的做法:

foo.h中

#ifndef Foo_H
#define Foo_H

int AAA(void);  // Just the prototype, not the function body

#endif

Foo.cpp中

#include "Foo.h"   // include the h file, although not strictly neecessary

// make the function and body
int AAA(void)
{
    return 0; 
}

Sketch.cpp

#include <Foo.h>  // include prototype, so the AAA function becomes known

void setup()
{
     ...
     AAA();   // call AAA somewhere
}

void loop(){

}

您可以在標頭中定義函數,因此您應該使用inline關鍵字:

inline int AAA(){return 0;}
//               ^^^^^^^^^^ definition

或者,僅將標頭中的聲明和實現.cpp文件中的定義放在一起進行編譯。

foo.h中

#ifndef Foo_H
#define Foo_H

int AAA();

#endif

Foo.cpp中

#include "Foo.h"

int AAA(){return 0;}

如果你的程序結構稍微復雜一點,它比Bbrado的答案要復雜一點。 你需要#include <Arduino.h>和#include幫助文件,如下所示:

testCall.ino

#include "testCall.h"
void setup() {
  AAA();
}
void loop() {
}

testCall.cpp

#include "testCall.h"
beeHive AAA(void){
    beeHive a;
    a.bee = (byte)1;
    a.hive = (byte) 2;
    return a;
}

testCall.h

#include <Arduino.h>
struct beeHive {
  byte bee;
  byte hive;
};
beeHive AAA (void); //  prototype only

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM