Question

The interface on my build system MacOS 10.6.3 for the POSIX math library is math.h, however on my target system the name of the interface file is cmath.h. At school we use cmath and I would like to be sure my project compiles when it is handed in, how is this achieved. The servers and workstations at school are x86 running Windows XP. The GCC is available on both platforms.

Was it helpful?

Solution

In the C++ standard, the math library functions are defined in two headers:

<cmath>

contains them in the namespace std (e.g. std::sin), while

<math.h>

contains them in the global namespace (so just sin).

There are further differences between the two: while <math.h> contains all the C math functions with distinct names for distinct types, such as

double sin(double);
float sinf(float);
long double sinl(long double);

etc., <cmath> contains overloaded functions such as

namespace std {
    double sin(double);
    float sin(float);
    long double sin(long double);
}

etc. (C++ libraries might additionally export sinf from <cmath>, but you can't rely on this in a portable program.)

Finally, the fabs, fabsf and fabsl functions from the C standard library have become overloads of std::abs in <cmath>.

Though both headers are in the standard, you should really prefer <cmath>, as <math.h> is only there for backward compatibility with pre-standard C++ and C.

There's no such thing as <cmath.h> in standard C++.

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