In C++, a class
is just that: a syntactical construct. You are free to arranges your classes across files as you want. You can put each class into it's own header/.cpp file pair, make header-only classes, spread them across many files - as you like.
In C++, you don't distribute classes, you distribute files. For someone to make use of your code, they would need all the declarations (of classes and everything else) for the compiler plus the definitions matching these declarations for the linker. (For what is a declaration and what is a definition see this answer).
Declarations are conventionally put into header files, in C++ usually with a .h
or .hpp
ending. (There are more conventions, but these are the ones I have seen most.)
Definitions can be distributed either in source (.cpp
files) or in their compiled form as object files. If more than one object file is needed, they are often assembled in a library (on Unix-like systems usually with an .a
ending, on Windows .lib
).
So these are the hard facts:
- You cannot avoid distributing header files. Period.
If you don't want others to see your definitions, you will need to compile them and distribute object files, preferably as a libary.
But distributing libraries definitely has its drawbacks. C++ doesn't define a binary API for compiled code, so code must always be compiled with the same compiler, the same compiler version, and the same compiler settings in order to be linked together.
That means you either must dictate your costumers their compiler settings (which is hard for them to accept if they have libraries from different vendors with - which is likely - conflicting settings) or you must cater for all their needs (which brings you into trouble).
Also, since everything in the headers is open to everyone's eyes, inline
functions' implementations are, by their very nature, unprotectable. But why use C++, when not using the performance gains they offer?
In the end, distributing source files is often easier. No offence meant, but as Neil put it: If you don't yet know the difference between classes and files and how to distribute them, it is very unlikely your giving away a fortune.