Go Down

Topic: Using libraries in libraries (Read 1 time) previous topic - next topic

mattallen37

So, you're saying I should declare all my library-specific variables in the .cpp file, instead of .h?

What I am doing now, is using #include <Wire.h> in the main sketch, and #include <C:\Program Files (x86)\arduino-1.0\libraries\Wire/Wire.h> in the header file. Why can't they fix the issues with the files? This is certainly not the only issue.

Nick Gammon


So, you're saying I should declare all my library-specific variables in the .cpp file, instead of .h?


Yes, the general technique is to put extern foo in the .h file and actually declare foo in the .cpp file in your library.

For example, HardwareSerial.

In HardwareSerial.h:

Code: [Select]
  extern HardwareSerial Serial;  // so it can be referenced in lots of places

In HardwareSerial.cpp:

Code: [Select]

// actually create the object:
  HardwareSerial Serial(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X);


Quote
Why can't they fix the issues with the files?


There are a few issues which "they" have not addressed just yet.

mattallen37

Okay, so what added scope would foo have if I did extern foo in the header (or what scope would foo have without putting it in the header file with extern foo)?

Nick Gammon

Without putting foo in the .h file it will have scope in the compilation unit in which it resides (ie. the .cpp file).

If it is in the .h file (with extern) it will have scope inside all the compilation units that include it. (In other words, they will get the same foo).

If you make foo static you will get a different foo in each compilation unit. Which isn't particularly useful, I suggest.

Nick Gammon

Making it "extern" basically says "the linker will sort it out".

But if you never have a "non extern" foo then the linker will say "I couldn't find the *real* foo" and the link will fail.

Go Up