如何将参数从Makefile传递到程序? [英] How to pass argument from Makefile to a program?

查看:42
本文介绍了如何将参数从Makefile传递到程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Makefile目录传递给函数.

I want to pass directory of Makefile to a function.

例如:

Makefile

$(DIR)=生成文件目录

程序

int main(int argc,char argv [])char目录= argv [1]

我该怎么办?

编辑澄清.我希望我的应用程序可以在我将其编译到的目录之外运行.

EDIT Clarificaion. I want my app to work outside of the directory that i compiled it in.

推荐答案

在编译时通过-D选项传递符号(示例是C ++,但是您可以轻松地转换为C).您可以只定义符号,也可以给它一个值(这就是您想要的值).

Passing a symbol at compile time is done with the -D option (example is C++ but you can transpose to C easily). You can either only define the symbol, or give it a value (which is what you want here).

DIR=$(shell pwd)
mytarget: 
    @echo "DIRECTORY=$(DIR)"
    $(CXX) mysource.cpp -D"DIRECTORY=$(DIR)" -o mysource

然后,在源文件中,符号 DIRECTORY 将包含路径.要对此进行检查,您需要一个额外的技巧(称为双重扩展"):

Then, in your source file, the symbol DIRECTORY will hold the path. To check this, you need an additional trick (known as "double expansion"):

#define STR1(x)  #x
#define STR(x)  STR1(x)
#include <iostream>
int main()
{
    std::cout << "directory is " << STR(DIRECTORY) << "\n";
}

您可以检查此类似问题

You can check this similar question, and see here about the D flag.

这篇关于如何将参数从Makefile传递到程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆