Question

So I'm writing a library and I want to define a constant that will have the value of pi. I was thinking of defining a static const float pi = 3.14; in a pi.h file.

However, I'm almost sure that's not the way to do it because I've read that you shouldn't define variables in header files.

Another way I thought was to declare an inline function that returns the value of pi but that's awkward to work with.

Another way (I think) is to put it in pi.cc compile it into the library and then use extern static const float pi; in whatever file you are using pi with and of course link those files with the library.

What's the best way of doing this? The standard library would probably define a macro but I think a constant is better.

Was it helpful?

Solution

One reason to not put a constant in a header file is to avoid recompiling the code using the library (rather than just re-linking) if the constant changes. This reason doesn't apply to constants such as π that never change as a program is maintained.

There is an additional issue if the constant is a floating point value. C++ requires that floating point constants have storage assigned to them and that they be initialized in a .cpp file, not a .h file. This can makes them the constants less efficient than the equivalent inlined functions. This is why the Boost library uses inline functions. See this answer.

So for your case, the best bet is probably to use the Boost library, or if you don't want to take the dependency, to just make an inline function that does the same thing.

OTHER TIPS

My suggestion is to place the constant in a header file. The constant will give the value type information which is a good thing.

Since the constant is not a variable, it can be placed in a header file.

you need to pull in the macro #define _USE_MATH_DEFINES as well

How do I access math constants (eg. M_PI) in Visual C++ 2008?

I see constant variables defined in header files often. Your idea of doing that seems reasonable to me. Making it static seems OK as well.

You also could divide your PI constant to two files, header and implementation. Having declaration and implementation separated you could change the value of pi (to more precise for example) without changing the interface.

This could by simple pi.h file:

extern float pi;

and pi.c:

float pi = 3.14;

I would make it static const but not extern and place it in a header file. static const tells the compiler that it's a constant variable accessible only in the current compilation unit. This allows the compiler to optimize away any actual storage for it and just use the value directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top