Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math interface vs cMath in C++

Tags:

c++

gcc

cmath

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.

like image 1000
awiebe Avatar asked Jan 04 '12 21:01

awiebe


People also ask

What is the difference between cmath and math?

The math module supplies mathematical functions on floating-point numbers, while the cmath module supplies equivalent functions on complex numbers. For example, math. sqrt(-1) raises an exception, but cmath. sqrt(-1) returns 1j .

Are cmath and math h the same?

[cmath] defines symbols in the std namespace, and may also define symbols in the global namespace. [math. h] defines symbols in the global namespace, and may also define symbols in the std namespace. if you include the former and use an unqualified symbol, it may compile with one compiler but not with another.

Can we use cmath in C?

The cmath header file contains definitions for C++ for computing common mathematical functions. Include the standard header into a C++ program to effectively include the standard header < math.

Is cmath standard library?

<cmath> is a standard library header of C++ which is extended from C header <math. h> and comes with namespace std . Since C++ 17, special mathematical functions were merged into the standard from TR1 and linear interpolation function (C++ 20) which were included inside <cmath> header.


1 Answers

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++.

like image 73
Fred Foo Avatar answered Sep 19 '22 14:09

Fred Foo