Search code examples
c++librariessqrtcmath

using only certain functions from a library?


i would like to use only certain functions from math.h (WITHOUT including the entire library)

for example, i need to use "sqrt" and "exp", but i have variables named "y1" (and possibly others) which conflict with definitions in math.h

how can i use only certain functions from a library like that?

i tried

#define sqrt cmath::sqrt

but that did not work, i have seen something like that before with

#define cout std::cout

i think, so i thought it might work.

any ideas?


Solution

  • Yes, you can just use the parts you want.

    Simply create your own partial mini_cmath.h header for those functions / globals you need access to (assuming those don't conflict!).

    As several have noted, there's no way to only #include a given chunk (unless the included header has preprocessor macros to enable such a thing, such as windows.h)

    But if you simply declare those functions you wish to use (correctly), and then compile & link (as long as the necessary .lib is included in your link), then you're golden.


    However, on a more general note - globals are a bad idea in general, but if you absolutely must use them for hopefully valid reasons, then you should be putting them in a namespace, and referencing them in your source by fully qualified name:

    namespace AcmeCorp {
      int g_fubar;
    }
    AcmeCorp::g_fubar = 9;