问题
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