c++ interface question - c++

I have
Package A (Namespace A), which has header file say internalItems.hpp, contains a class with enumeration of items to be created and methods to get and set item type.
Now this class has to be made available in common package (Package Common with Namespace COMMON) so that other package (let says Package EndUser with Namespace EUSER) can use enumeration type.
What is the best way to do it ?
Thanks you for your valuable responses.

I think you're asking how to expose the classes and enums in internalitems.hpp to your EUSER project from your Common library.
You're going to have to #include "internalitems.hpp" in any file that needs to use the enums or classes defined in it, no matter which project they're in. In that case if internalitems is intended to be an internal, not-exposed-to-library-consumers header file then you'll need to promote so it is part of the Common library interface headers or at least filter out the parts that the external code needs to use into a public header file.

Related

Is the Object-Class reationship in C++ different from other languages, say Java and C#?

I've been programming in Java and C# for a while and I guess I always thought of objects and classes as being one and the same but the C++ course I'm following has the classes in .h files and the objects .cpp files. Is this typically how a C++ program is structured? Is the class/object relationship different than other OOP's?
You might as well see classes declarations in a .cpp file, e.g., if the one who wrote this file decided to use some help-classes that weren't supposed to be part of the API presented in the .h file.
Also, you might see in a .h file an object that is being held within a class as its private member.
Indeed, Java "pushes" you towards a pretty strict source and class files organization, that in many cases will match your folders & files organization. C++ allows you much more freedom in this regard, but however has the notion of includeing header files.
The relationship between the class and the object is not different to other languages. The object is an instance of the class.
So for example:
Car myCar("licence-plate123");
Car is the class. myCar is an instance of the Class Car and therefore the object.
To seperate the Class declaration is more like a convention and has nothing to do with objects and classes.
The .h-File contains the class description. There you can see, which methods the class provides, and what parameters they need. The .cpp-Files describe how each method works. So the actual source-code.
But as I have already said: This is more like a convention. You can also write all of it in the .h-File. It's not pretty but it works

abstracting c++ enums to reduce compilation

In my code I have a central data storage that is referenced into via enumerated symbols. This allows me to see all the places in my code where the enum'd symbol is referenced for setting/getting a value. The problem comes in whenever I want to add a new symbol it requires that all of the code that might access the data storage be recompiled because all of it touches the enum header file.
Is there some abstract that would reduce recompiles? Maybe a design pattern?
That's the problem you have with a "central data storage" as you called it. That sounds like an excuse for putting all of the enums you don't know what to do with in a single header file.
If an enum is related to a class and used only when that class is used, put it in the same header file as the class. If your enums are really all stand alone, you can still divide that header file into multiple header files that have more specific categories of enums in them.
Only thing you can do is to use strongly typed enums, if you have access to c++11 features. Then you can forward declare the enum, and you do not have to include that header in other headers needing the enum.
For pre-c++11, nothing can be done to prevent the recompilation.

Where should support function declarations go?

I have a .cpp source file with some functions that need to be publicly accessible and some support functions that are only used in this source file.
I have been putting the all of these functions declarations in the header file as I personally find it useful to see everything a class offers in one place. However I would like to indicate whether the functions are for internal use, similar to the private access modifier, but without using classes (they are standalone functions).
Some possible solutions are:
Put the private declarations in the source file.
Put the private declarations in a separate header.
Both of these solutions split the public and private functions into separate files which I would like to avoid.
If the functions are not intended for public use, the shouldn't be placed into the header. Put them into the source file they are used in.
To completely hide these functions from being used outside the source file one of the following is usually done:
Functions are declared as static.
Functions are put into an unnamed namespace.
The latter is considered preferable. Actually, the C++ Standard 7.3.1.1 states:
The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.
For more discussion about unnamed namespaces vs static refer to Unnamed/anonymous namespaces vs. static functions and to corresponding comp.lang.c++.moderated thread.
If the private functions are only used in a single source file, then you don't need any extra header file. Just mark the functions either static or use an anonymous namespace.
If the functions can be used from many source files, declare them in a separate header file in a special namespace. That's my advice.
Where should support function declarations go?
They don't have to go anywhere. Make them static and keep them in source file. If they're only used in single source file, there's no need to put forward declarations into any header.
You don't mention whether these 'functions' are members of a class but I'll assume that they are. If so, I would recommend that you look at the 'pimpl idiom'. Basically this means putting all or most of what you want to keep private into a seperate class and then only having a pointer to an instance of the class in your class declaration. For example:
class MyClass
{
// ... some stuff
private:
SecretObject obj_;
int hiddenCall();
};
becomes
class MyClassImpl;
class MyClass
{
private:
MyClassImpl* impl_;
};
The idea then is that all the declaration and definition of your implemntation class would go into your .cpp file which hides it from anything but the compilation unit. This approach has a number of important advantages:
Hides implementation so the publicly available header does not give too much of the implementation away.
Can increase compilation speed by removing dependecies in the header - v. important if the header is included a lot.
Can be useful for 'insulating` client code against libraries that they shouldn't need to build against such as database APIs etc.
There are a number of drawbacks:
Can make unit testing more tricky if code is hidden away in cpp files. Personally I find a better solution is to have a seperate, private header and implementation file so you can control what clients of your code get but a test harness can still test it adequately. You can simply include the MyClassImpl header in your cpp file, but don't include it in the MyClass header - this would defeat the object.
The indirection between MyClass and MyClassImpl can be tiresome to code / manage.
Generally though, it's probably the best way of acheiving what you want to get to. Look at articles by Herb Sutter for a more in depth explaination.
On the other hand, if you are talking about free functions, not directly related to the class, then I would put these within the unnamed namespace within your cpp file. For example:
namespace {
// Your stuff goes here.
};
Again, you've got a unit test issue of how to access these functions if you take this approach, but it's possible to work around this if that's really an issue, perhaps by creating a specific namespace, conditional compilation etc. Not ideal, but possible.

What is best practice for C++ Public API?

What is best practice for C++ Public API?
I am working on a C++ project that has multiple namespaces, each with multiple objects. Some objects have the same names, but are in different namespaces. Currently, each object has its own .cpp file and .h file. I am not sure how to word this... Would it be appropriate to create a second .h file to expose only the public API? Should their be a .h file per namespace or per object or some other scope? What might be a best practice for creating Public APIs for C++ libraries?
Thanks For Any Help,
Chenz
It is sometimes convenient to have a single class in every .cpp and .h pair of files and to have the namespace hierarchy as the directory hierarchy.
For instance if you have this class:
namespace stuff {
namespace important {
class SecretPassword
{
...
};
}
}
then it will be in two files:
/stuff/important/SecretPassword.cpp
/stuff/important/SecretPassword.h
another possible layout might be:
/src/stuff/important/SecretPassword.cpp
/include/stuff/important/SecretPassword.h
G'day,
One suggestion is to take a look at the C++ idiom of Handle-Body, sometimes known as Cheshire Cat. Here's James Coplien's original paper containing the idiom.
This is a well known method for decoupling public API's from implementations.
HTH
I'd say it's best decided by you, and the type of 'library' this is.
Is your API provides one "Action"? or handles only one abstract "Data type"? examples for this would be zlib and libpng. Both have only one header that gives everything that is needed to perform what the libraries are for.
If your library is a collection of unrelated (or even related) classes that do, or not, the same goal, then provide each subset with it's own header. Major example for this will be boost.
Here is what I'm used to do:
"Some objects have the same names, but are in different namespaces"
That's why namespaces exist.
"Would it be appropriate to create a second .h file to expose only the public API? "
You always should expose only the public API. But what means to expose public API? If it would be only to headers then, since public API relies on private API, the private API would be included by public API anyway. To expose a public API mark public functions/classes with a macro (which in case of Windows exports public functions to the symbol table; and probably it will be soon adopted by Unix systems). So you should define a macro like MYLIB_API or MYLIB_DECLSPEC, just check some existing libraries and MS declspec documentation. It is sufficient, usually non-public API will be kept in subdirectories so it doesn't attend library's user.
"Should their be a .h file per namespace or per object or some other scope?"
I prefer Java-style, one public class per header. I found that libs written in this way are far more clean and readable than those which are mixing file and structure names. But there are cases when I brake this rule, especially when it comes to templates. In such cases I give #warning message to not include header directly and carefully explain in comments what is going on.
Great response LiraNuna.
Are you providing an API to an application or a library?
An application API will generally only provide methods that either query the state of an application or attempt to alter that state. In this case you'd generally have separate interface declarations in a separate header file. Your objects would then implement this interface to handle API requests.
A library will generally expose objects that can be re-used. In this case, generally speaking, your API is simply the public methods in the header file.
I agree with what doc said - one class per file. 99.9% of the time!
Also, consider what filenames to use. It's generally a bad idea to have multiple headers of the same name in different directories, even though the classes they contain may well be in different namespaces.
Especially if this is a public API, you probably cannot control what include paths are defined by the user of your library, so a build may find the wrong one. Tweaking the order of include paths would definitely not be a solution I'd recommend!
We use a naming convention of Namespace-Class.h to explicitly identify classes in files.

DLL library interface

I have a question that bothers me for a long time.
I have a mathematical library, implemented as DLL.
The library implements many types of mathematical functions.
The mathematical functions are implemented in different classes based on their functionality. For example, all functions that implements polynomial equations are under CPolynom, all functions that implements differential equations are under CDifferential.
The DLL has to expose an interface.
Now my question:
Option 1
I can implement in one header file, one interface class which includes all the “sub” interface methods of all practical classes => On one hand, I expose to the outside world only one header file with one class, on the other hand this class might be huge, including interface methods which are not related (i.e. someone wants the CPolynom functionality, he/she will have to include huge header file and construct huge interface class)
Option 2
I can implement interface class for each class in different header file.
=> On one hand I split classes to different files based on functionality. If someone wants a specific functionality, he/she will have to include only the relevant file.
On the other hand, I can end up with many header files introduced to the outside world.
Which approach counts as more professional, more correct in software design discipline?
Thank you,
David
I generally implement one header per class. If you find yourself always needing a shotgun blast of headers because you need "one from column A and two from column B", that generally implies some sort of design code smell. For instance, you have a single responsibility spread across several classes instead of concentrated in a single class.
Well, you could always go for option 2 and create a header, that will include all other headers, so that way, if someone doesn't care, he will just include 1 big header, otherwise, he will be able to include only what he needs.
Personally, I don't see anything wrong with one big header, when I try to use small headers as an user, I always have problems like "I need only 1 function from header X, 2 from header Y, ...." and after all, I end up with 15 includes to one library in each *.cpp file, which is annoying (so I actually create one big header myself :) ).
I think that you should implement interface for each class and put them in one header file. No need to produce lot of library headers in the world of precompiled headers.
One header (or few, if there is a lot of interfaces and you can group them logically), but separate classes is an option too. Don't make one huge class with bunch of methods like you were going to do in option 1.
The size of the header file is relevant only in terms of how long it takes to compile. Unused declarations will not impact performance, and your code size is already impacted by shipping all the functions in a DLL instead of statically linking only the needed functions.
Have you considered putting a COM interface on the library? Instead of shipping a separate .h file your users can simply:
#import "mathFunctions.dll" named_guids
Automatically declared smart pointers then make the functions usable with no further manual declarations or even cleanup. You can define your documentation in the IDL, which will then appear in tooltips in the IDE when your clients go to use your code. Your code is also reusable in all Microsoft languages from VB3-6 and wscript and .Net.
double myFunc(double x)
{
double a=1, b=2, c=3, y=0;
MathLib::PolynomPtr polynom(CLSID_CPolynom, 0, CLSCTX_INPROC_SERVER);
y = polynom->someFunction(a, b, c, x); // use it somehow
return y;
}
Used in-proc, COM adds only about 16 cycles of overhead to the execution of each function. Because it's a smart pointer, you do not have to clean it up. And I didn't include it above, but as with anything external you should add basic try/catch functionality wrappers:
catch (_com_error &e) { printf("COM error: %08x %s\n", e.Error(), e.Description()) };
Option 2 would look natural and professional to everybody.
This is the way the large majority of libraries are done.
However, grouping small related classes in the same header (but still having several headers for the whole API) sounds very reasonable.
The biggest disadvantages I see of option 1 are:
- Everything in a big class might be difficult to handle: when a developer is busy on using CPolynom, having its declaration lost between CDifferential and other class would be painful.
- Using a namespace is more appropriate to aggregate classes, than a bigger, "mother" class.
In short, I would choose option 2, with all classes under the library namespace.