Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include specific function from a header file into the code in c++

In python, one can import specific feature-sets from different modules, rather than importing the whole file

ex:

Instead of using import math and using print math.sqrt(4), importing the function directly:

from math import sqrt
print sqrt(4)

And it works just fine.


Where as in C and C++, one has to include the whole header file to be able to use just one function that it provides. Such as, in C++

#include<iostream>
#include<cmath>
int main(){
    cout<<sqrt(4);
    return 0;
}

C code will also be similar (not same).


Is it possible that just like as it was in case of python, one can include just one function from a header file into their program?
ex: including just the sqrt() function from cmath?

Could it be done?

like image 794
zhirzh Avatar asked May 31 '14 21:05

zhirzh


1 Answers

No, it is not possible. C++ lacks a true module system, so we are left with preprocessor includes. A proposal to add a new kind of module system did not make it into C++11. See C++ Modules - why were they removed from C++0x? Will they be back later on? for more information on that proposal.

If this is about your own library, your only chance is to split the library into smaller, independent libraries. If the library is not yours and/or you cannot change it, you'll have to live with it. But what's the real problem, anyway?

like image 195
Christian Hackl Avatar answered Sep 22 '22 00:09

Christian Hackl