user198729
user198729

Reputation: 63686

Why can CImg achieve this kind of effect?

The compilation is done on the fly : only CImg functionalities really used by your program are compiled and appear in the compiled executable program. This leads to very compact code, without any unused stuffs.

Any one knows the principle?

Upvotes: 2

Views: 379

Answers (3)

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248199

CImg is a header-only library, and they use templates liberally, which is what they're referring to.

If they used a precompiled library of some kind (.dll/.lib/.a/.so) the library file would have to contain the entire CImg library, regardless of which bits of it you actually use.

In the case of a statically linked library (.lib or .a), the linker can then strip out unused symbols, but that may depend on optimization settings.

When the entire library is included in one or two headers, it is only actually compiled when you #include it, and so it is part of the same compilation process as the rest of your program, and the compiler can easily determine which parts of the library are used, and which ones aren't.

And because the CImg API uses templates, no code is generated for functions that are never called.

They are overselling it a bit though, because as the other answers point out, unused symbols will usually be stripped out anyway.

Upvotes: 6

Necrolis
Necrolis

Reputation: 26181

This sounds like MSVC's Eliminate Unreferenced Data (/OPT:REF) linker command, GCC should have something similar too this too

Upvotes: 0

Will A
Will A

Reputation: 25008

Sounds like fairly standard behaviour to me - a C++ linker will usually throw away any unused library references rather than including uncallable code. Similarly, an optimized build will not include uncallable code.

Upvotes: 2

Related Questions