I am planning to write a code library to access some hardware at a low-level (i.e. flipping register bits and such).
Previously, I wrote everything as C functions and used extern ‘C’ to make the library compile for both C and C++ code. So, both C and C++ users merely had to include the header file and call the functions as they were.
Now, I am thinking of organising things as classes. For example, I can put all the functions to initialise, configure, transmit and receive a UART in a class. This works fine in C++ but how about C? I can’t extern ‘C’ an entire class.
One thing that I was thinking of: write everything in standard C functions escaped with extern ‘C’. Then, provide a wrapper class for C++, that has a bunch of inline methods that call these ‘C’ functions.
int foo_bar (int *address, int data) {...} // extern C stuff int foo::bar (int *address, int data) { return foo_bar(address, data); } // inline method
Is that okay? Any other ideas? Best practices?
There is some precedent for what you’re proposing – Microsoft’s MFC classes are just C++ wrappers around the C-compatible Windows API.
Before you start though, you should have some goal in mind beyond just creating busywork for yourself. The C++ should be easier to work with than the C, or you’re not gaining anything.