Header-Only Library

Hi,

Up until this point, I have been using LIB files to construct libraries. However, I would like to experiment with header-only libraries. Is the following simple example acceptable practice?

Interface header (functions.hpp)
1
2
3
4
5
6
7
8
#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP

double fnc();

#include <functions_implm.hpp>

#endif 


Implementation header (functions_implm.hpp)
1
2
3
4
5
6
7
8
#ifndef FUNCTIONS_IMPLM_HPP
#define FUNCTIONS_IMPLM_HPP

double fnc() {
	return 987.34;
}

#endif 


Calling function in library
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <functions.hpp>
using namespace std;

int main(int argc, char * agrv[]) {
	double var = fnc();
	cout << var << endl;
	return 0;
}


Thanks...
This is what you want for a header-only library:

1
2
3
4
5
6
7
8
9
#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP

inline double fnc()
{
	return 987.34;
}

#endif 


The "implementation header" is not needed. And you call the function in the same way.

The key here when doing a header-only library is that your functions are all declared inline.
Hi PanGalactic,

Thanks for your reply. Would you mind answering a couple of clarification questions please?

1. For a simple example such as this one, one header file would be appropriate. However, in practice I will have many functions/classes and would like to keep the interface header as free of clutter as possible. In this case, would you still recommend merging the two files?

2. Assuming that I kept the two separate headers, should I inline both the prototype and the definition of the function?

Thanks again…
1) I would think it would depend on your own preferences. All of the header only libs I've seen are all in one file though, maybe to reduce the # of files.

2) I would do both, but you only need one.
OK. Thanks for taking the time to post an answer.
Topic archived. No new replies allowed.