开发者

Is there a way to create EXE static-linked file without the default libs, so the EXE size will be much smaller? C++ Visual studio

开发者 https://www.devze.com 2022-12-07 18:51 出处:网络
**My main assignment is to make the EXE file size as smaller as possible. ** I\'m currently working on program which make use of:

**My main assignment is to make the EXE file size as smaller as possible. ** I'm currently working on program which make use of:

#include <iostream>
#include <vector>
#include <string>
#include <array>
#include <windows.h>
#include <bcrypt.h>

#pragma comment (lib, "bcrypt.lib")
#pragma comment (lib, "kernel32.lib")

As I compile and link the code with /MT and /NODEFAULTLIB I get the unresolved external symbols LNK 2001 and 2019 such as:

error LNK2001: unresolved external symbol "const type_info::`vftable'" (??_7type_info@@6B@)
error LNK2001: unresolved external symbol "class std::basic_istream<char,struct std::char_traits<char> > std::cin" (?cin@std@@3V?$basic_istream@DU?$char_traits@D@std@@@1@A)

When I use the default libs I see the libraries it imports objects from:

libcmt.lib
libcpmt.lib
libucrt.lib
libvcruntime.lib

As I understand, those libraries contains the functionality so I must use them and to disable them

But on the other hand, they make my static-linked exe file heavy

What can I do to reduce my EXE file size to the minimum? I thought about changing the functions I use (I mean, stdio.h instead of iostream for example) Any other thoughts and suggestions for steps I can make?

I tried to:

  • disable by /NODEFAULTLIB
  • using /Gs- so no security will be needed
  • using 开发者_JAVA百科/Os /O1 and other optimazations

I also tried to replace iostream with stdio.h and replaced all std::cout, std::cin and std::cerr with printf() and scanf() It did reduced me like 62KB (from 179KB to 117KB) But as I instructed, I can manage to reduce it even lower


There are multiple reasons why the IDE may throw linker error LNK2001, as it verbalizes on its own it can't find the any definitions matching the declared signature. This often arises from libraries not being correctly linked, missing definitions, but also if you try to link libraries of a different configuration and/or language version. Microsoft has a handy documentation over the LNK2001 error.

Remember that you can't link a Release library to a debug configured application, and same goes for debug library to Release application.

  • /MT (Release)
  • /MDd (Debug)

Now if you have the source code for your libraries I recommend that you compile them down to dlls since they can be loaded in runtime. And therefore should decrease the size of your executable.

0

精彩评论

暂无评论...
验证码 换一张
取 消