Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best practice for C++ Public API?

Tags:

c++

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

like image 955
Crazy Chenz Avatar asked Nov 08 '09 23:11

Crazy Chenz


People also ask

What makes a good API?

A good API must be able to limit the amount of data that can be received in one go, as well as the frequency of requests for data. It should also be able to notify about how many “pages” of the data are left.

What are API guidelines?

API style guides, or API guidelines, are easy-to-consume references and instructions for all of the important information that a team will need to create or work with APIs.

Can we build API using C++?

Normally yes. Generally: If source is to be available, use header only (if templates) or h +cpp. If no source, the best is DLL. Static libraries - you have to build for many compilers and one has to carry on your lib everywhere and link to it.


2 Answers

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
like image 133
shoosh Avatar answered Oct 23 '22 10:10

shoosh


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

like image 24
Rob Wells Avatar answered Oct 23 '22 09:10

Rob Wells