Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed .exe file into C++ program?

I wrote a c++ program and I want to execute my second program inside it, which is a exe file. The problem is I want to share my program to others as one single file.

When I search on the internet, I found this solution.

Just store the second .exe file as a binary resource inside the main .exe using an .rc file at compile-time. At run-time, you can access it using FindResource(), LoadResource(), and LockResource(), and then write it out to a temp file on disk before passing it to system().

But I don't understand how to "store the .exe file as a binary resource"

I am currently using CreateProcess() to start my second program which working greatly. Can anyone write some example for me?

like image 282
Jason Lam Avatar asked Sep 17 '26 11:09

Jason Lam


1 Answers

In your project's resource script (the .rc file in which icons, dialogs, etc. are defined), you can add a binary resource with a line like the following:

IDB_EMBEDEXE    BINARY      "<path>\\EmbedProgram.exe"

Where the IDB_EMBEDEXE token/macro should be defined in a header file that is included by both that resource script and any C++ source(s) that use(s) it; this will be the lpName argument given to the FindResource() call, which you can form using MAKEINTRESOURCE(IDB_EMBEDEXE). Specify "BINARY" (or L"BINARY" for Unicode builds) for the lpType argument.

Like this:

#define IDB_EMBEDEXE 13232 // Or whatever suitable value you need
//...
// In the C++ code:
HRSRC hResource = FindResource(NULL, MAKEINTRESOURCE(IDB_EMBEDEXE), _TEXT("BINARY"));
HGLOBAL hGlobal = LoadResource(NULL, hResource);
size_t exeSiz = SizeofResource(NULL, hResource); // Size of the embedded data
void*  exeBuf = LockResource(hGlobal);           // usable pointer to that data

// You can now write the buffer to disk using "exeBuf" and "exeSiz"

The specified executable file will then be completely embedded (as a binary) resource in your built executable, and can be extracted, written to disk and executed as described in the article you quote.

like image 95
Adrian Mole Avatar answered Sep 19 '26 23:09

Adrian Mole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!