简体   繁体   中英

How to import functions in c++ without importing the whole library

Just wondering if i can import things like sort without importing the whole lib? If its possible can you please explain to me how to do so and if not could you tell me why?

Assuming a function is in a library in the first place (and not just a header-file implementation), then linking to that library SHOULD only pull in the function(s) you are using [including, of course, ones that are used internally]. So there is really no reason to avoid linking with a library that provides something you need.

Of course, the implementation may be silly and use lots of functions that you don't ACTUALLY need for what you want to do, but this is a separate problem.

For template-functions (which, in almost every current compiler, has to be implemented in a header-file), the requirement is to include the appropriate header-file.

At the moment, you can't import individual functions from a header, you can only #include the entire header. While you don't need to include the entire standard library to use std::sort() , you do need to #include <algorithm> , and by extension include all the algorithms. However, the compiler is usually smart enough to only put the library members you use in your executable; it's not likely to compile std::copy() into your program if the only member of <algorithm> you use is std::sort() , for example.

C++ may be getting this functionality in the future, however. One of the things they were looking at for the C++17 standard is modules, which would theoretically allow for functionality similar to what you want (I believe). While it currently doesn't appear that they'll actually make it into C++17, they may still be released as a Technical Specification, which most major compilers would likely try to incorporate if it's feasible for them to do so.

If you means by lib the windows .lib output of static library built. The answer is no. You can not link to part of it without the other. However, if you have the whole source, yes you can do some trick and clean the unnecessary part then built it again and link to it.

EDIT:

I have just notice the sort word. If it is really the std::sort , then you have misunderstood something. Like Igor said in the comments:

it's a template function implemented entirely in headers. You don't "import" any library for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM