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

痴心易碎 提交于 2020-01-05 08:48:18

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/23974642/include-specific-function-from-a-header-file-into-the-code-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!