leomil72 / swRTC

swRTC is a library that implements a software-RTC on an Arduino board or an Atmel microcontroller
36 stars 16 forks source link

The library doesn't compile when the sketch logic spans multiple files #10

Closed dan1994 closed 4 years ago

dan1994 commented 4 years ago

Environment: VScode 1.41.1 with the Arduino extension 0.2.28.

I have a sketch (src.zip) with multiple files:

src
| -- sketch.ino
| -- SomeClass.h
| -- SomeClass.cpp
| -- TimeKeeper.h
| -- TimeKeeper.cpp

The files contain no logic at all, but form the following include hierarchy: TimeKeeper.h includes <swRTC.h>. TimeKeeper.cpp includes TimeKeeper.h. SomeClass.cpp includes SomeClass.h sketch.ino includes SomeClass.h and TimeKeeper.h

When trying to compile I get a linking error for multiple definitions of the functions in the library (compile log attached with sources).

I believe this is caused because you define your functions in swRTC.h rather than in a separate .c file.

This doesn't reproduce without SomeClass.h and SomeClass.cpp (I don't understand why).

leomil72 commented 4 years ago

I included the whole code into a .h file because in this manner the user doesn't have to initialize the library before to use it. Said this, the other issue I see is that you tried to include swRTC.h into TimeKeeper.h while you should include it from TimeKeeper.cpp, and the compiler, by seeing the inclusion into .h file, compile the swRTC.h file several time, keeping in the errors you encountered.

dan1994 commented 4 years ago

I don't know about the Arduino IDE and other environments, but VScode automatically detects libraries and compiles their sources, so there's no need to do anything different even if you seperate the defintion to cpp files.

But even if it does require more work from the user, it's the correct way to manage c++ code, and I've seen many Arduino libraries that work this way.

In my particular case the TimeKeeper class had an instance of the swRTC class, and for that reason I had to include swRTC.h in TimeKeeper.h.

leomil72 commented 4 years ago

I understand your needs but when I wrote this library I chose to integrate both headers and code into a single .h file for some particular reason. That is not a strange solutions since it's allowed by C/C++ and it's also a method used by other libraries, too. I'm sorry but at the moment I don't have any real interest into reverting the library and fragment the code into a .cpp and a .h file. Maybe in the future.

dan1994 commented 4 years ago

Okay. Thanks for your reply.