简体   繁体   中英

Add files to c++ executable file

I am compiling a c++ file as an executable file. I am using

g++ -std=c++11 your_program.cpp -o your_program

to compile the program, and

sudo chmod a+x your_program

to create the executable file. I have 2 .txt files and a .csv file that are needed for the program to function correctly. Every time I run the executable, I get the statement that says the files weren't opened. Is there a way I can include these files when I am making it an executable file? The files are all in the same directory.

" Every time I run the executable, I get the statement that says the files weren't opened.

That's probably because you run it with a different current directory than the file opening statements assume.

Unfortunately there is no guaranteed standard library way to obtain the executable's own directory. However, with the C++17 filesystem library you can form a complete path from (the main function's) argv[0] , and drop the last item of that path. In most cases that will get you the executable's directory, and then you can form absolute paths for the support files.

" Is there a way I can include these files when I am making it an executable file?

Many.

Different OS-es provide different APIs for such resources (data embedded in executable), which one might be tempted to use. Unfortunately there's no abstraction over that in the standard library. That means it's not easily portable.

Since your files are all text files you can however simply embed them as string literals in your code.

One simple way for a header file is like this:

#pragma once

inline auto my_text()
    -> char const*
{
    char const* const s = R"unique-id(
blah
blah blah
blah blah blah
)unique-id";
    return s + 1;
}

While string/array literals in your code is foolproof, there is usually a better way. There is an old article (Linux Journal, IIRC) that deals with this specifically.

There is an entire article about it here: Gareus: Embedding Blobs in Binaries . The technique is the same, just with a little care to handle cross-platform issues.

Sorry, this is a link-only answer; the full content is easily searchable online and would be too much to replicate here.

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