Arduino library: several function definitions

Today I ran into some strange problem while trying to use the IRremote library, and I was able to fix the problem as follows. If you have a folder in the libraries, with Foo.h and Foo.cpp inside, and write sketch to enable Foo.h:

foo.h

 #ifndef Foo_H #define Foo_H int AAA() { return 0; } #endif 

foo.cpp

 #include "Foo.h" 

Sketch

 #include <Foo.h> void setup(){ } void loop(){ } 

Error message:

  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 

I am using a 32-bit Windows 7 machine. Tested on Arduino 1.0.5, 1.0.4 and 21, 22.


So, with some research, I realized that the problem is due to my preprocessor confusion and binding. This question explains how the preprocessor includes a file and includes security:

Here are some of the pages that helped me understand:

And this is the best explanation of the built-in specifier:

+4
source share
4 answers

Well, you defined the function in two places: once in Foo.cpp, where it includes the title, and again in your sketch, where it includes the title. The C and C ++ headers do not provide a modular system; they are simply literally inserted instead of the include statement.

Declare AAA in the header, but define it in Foo.cpp (so there is only one definition) or mark it inline .

+10
source

Well, the distribution of materials in your files is perhaps more than unusual.

Here is how it is usually done:

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(){ } 
+3
source

You define the function in the header, so you should use the inline :

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

Alternatively, only the declaration in the header and the definition in the .cpp implementation file should be compiled.

foo.h

 #ifndef Foo_H #define Foo_H int AAA(); #endif 

foo.cpp

 #include "Foo.h" int AAA(){return 0;} 
+1
source

This is a little more complicated than Bbrado's answer if the structure of your program is a little more complicated. You need #include <Arduino.h> and # include a help file, as shown below:

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 
0
source

Source: https://habr.com/ru/post/1486225/


All Articles