我有以下文件夹结构:
include/
src/
data/
binary-file
makefile
我会像这样执行二进制文件:./binary-file
但现在我希望我的二进制文件像这样放在它自己的文件夹中:
bin/ <- binary-file is in here now
include/
src/
data/
makefile
当我像这样从主文件夹执行它时一切正常:bin/binary-file
但是如果我在主文件夹之外的另一个文件夹中,程序将无法正常运行并且无法找到#include 的路径。例如,如果我在 bin/文件夹中,如果我这样执行它,程序将表现不佳:./binary-file
我的问题是:如何让我的 makefile 或二进制文件像在主文件夹中一样从我系统的任何地方执行?
在我的 makefile 中,我所做的更改是:
$(CC) $(CFLAGS) -I$(IDIR) -I$(BDIR) -I$(DDIR) -o $(PROG) $^ $(LFLAGS)
到
$(CC) $(CFLAGS) -I$(IDIR) -I$(BDIR) -I$(DDIR) -o $(BDIR)/$(PROG) $^ $(LFLAGS)
最佳答案
好的,基于你最近的通讯
@thurizas I have some data in my DDIR that my binary uses ("data/xml/file.xml"). When I execute the binary from the main folder: /bin/binary-file, everything works. But when I execute the binary file from the /bin/ folder: ./binary-file, it is unable to load "data/xml/file.xml"
硬编码数据文件的绝对路径(比如/home/brandonto/projects/data/xml/file.xml .... 假设一个 *nix 类型的文件系统)。显然,无论您的可执行文件位于何处,它都可以找到数据文件。不利的一面是,如果您移动二进制文件,它将停止工作。
添加一个命令行选项来设置数据路径。例如,假设您选择应用程序数据文件的默认位置为
/usr/share/brandonto/myapp/data
,您可以将其硬编码到您的应用程序中。现在允许用户使用命令行参数来调整找到文件的位置。您的逻辑是,如果给出了命令行参数,则使用它,否则使用默认位置。有利的一面是您可以从任何地方执行,用户可以根据个人喜好移动内容,并且如果需要,您可以拥有两组数据文件(比如一组用于测试,一组用于生产)。不利的一面是,您的程序变得有点复杂,如果用户确实将数据文件移动到某个不寻常的地方,则每次他启动应用程序时都必须输入更多内容。例如;./myapp -- would use the default location for the data files ./myapp -f <somepath> -- would use the files in <somepath> over ridding the default
还有一些其他选项,例如配置文件(这让我们回到与您最初的问题非常相似的问题:))
关于c - Linux/生成文件 : Creating a binary that executes as if it were in a specific directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28548221/