How to pass argument from Makefile to a program? [closed]

匆匆过客 提交于 2021-01-28 07:21:50

问题


I want to pass directory of Makefile to a function.

For example:

Makefile

$(DIR) = makefile directory

program

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

How can I do that?

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


回答1:


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

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.




回答2:


In case the directory you need to pass is static (i.e. always the same) you can use the -D C compiler option:

cc -DDIRECTORY=/home/user/...

In your C source code you can then use DIRECTORY.



来源:https://stackoverflow.com/questions/48261350/how-to-pass-argument-from-makefile-to-a-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!