Declare class object in libary header

I’m trying to create a library to to simplify my project and reuse elements in future projects.

I have a class that is declared in the libary .h and defined in the .cpp

I would like to create a class object inside the library, but my issues are…

If i create it in the .h i get a multiple definition error (which i understand)

If i create it in the .cpp no errors, but its not available in the project that includes the library.

If i create the class object in the project this works fine, but it would be preferable for it to created inside the library.

Maybe its fundamentally wrong to think of doing this - but if not any ideas gratefully received.

you can instantiate in the .cpp, that’s the right place but ensure you advertise its existence in the .h by using the extern keyword

for example in the HardwareSerial class that’s what they do. You can see

extern HardwareSerial Serial; 

and at the end of each dedicated subclass you can see they are instantiating the object

HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);

( a bit complicated with the ifdefs to take into account various hardware but that’s the idea)

1 Like

Thank you again for your help :slight_smile:

Creating a library was way beyond my c++ knowledge - but i’m learning so much on the journey, its proving worthwhile for that alone.

learning is a great exercise and it keeps you alive :slight_smile:

have fun

This seams like it is ‘forward declaration’ , is that right ?
or is it technically something else.
cheers

If you are creating a library, this may be interesting. Post # 5 shows a useful guide on managing the .h and .cpp contents. It doesn’t handle specialties for, example templates etc. , which have their own requirements, but should help to get started.

thanks - that was a good read.

kind of for variables yes. With extern you tell the compiler something like I am going to use this variable name of this type, you don’t know yet where it is defined (memory allocated) but I promise everything will become clear later at link time

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.