0

Edit:

This is different than the other question because the variables that I put on the unix command line will be "p2 -s input.txt", where my main.c file will manipulate them.

So normally when working with command line arguments, my code would be something like:

int main(int argc, char argv[])
{ 
     printf("%d", argc);
     return 0;
}

How would I do this with a makefile?

John
  • 55
  • 2
  • 8
  • What would you like to do with your makefile? – Elias Garcia Feb 26 '16 at 02:53
  • The arguments to `make` are used to determine which targets to build. – Barmar Feb 26 '16 at 02:55
  • Possible duplicate of [Passing additional variables from command line to make](http://stackoverflow.com/questions/2826029/passing-additional-variables-from-command-line-to-make) – Trevor Hickey Feb 26 '16 at 02:58
  • Basically I want to type " p2 -s input.txt " I know this for a totally different program I just want to understand the basic idea behind it – John Feb 26 '16 at 03:15

2 Answers2

2

GNU make is not C.
Passing arguments cannot be done the same way.

If you'd like to provide custom arguments to your makefile,
you may consider doing this through variable assignments.

for example, take the following makefile:

all:
    @echo $(FOO)

It can be called via the command line like this:

make FOO="test"  

and it will print test.


Other options to consider:

  • setting environment variables before calling make
  • relying on different targets specified inside the Makefile
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • I called the program p2. When I want to run the program I would put "p2 Hi" and it should print 2. I want to pass the arguments of "p2" and "Hi" to my main.c program – John Feb 26 '16 at 03:18
  • @John Maybe I misunderstood. So you want your makefile to take in arguments, and then have those arguments passed into your C program? There is nothing stopping you from forwarding those arguments in the body of a 'make' rule. Instead of the echo command shown above, you could call your own program. – Trevor Hickey Feb 26 '16 at 03:26
  • Sorry it is hard to explain this in words lol. Do I have to change the parameters for my main.c then? I tried to check if -s was argv[1] (which it should be) but whether I try strcmp or == it still returns that the flag is not there. The more confusing part is that I also included a test print statement-- printf("%s", argv[1]); and it printed -s – John Feb 26 '16 at 03:48
0

Use a makefile like this:

COMMAND = echo 'You did not specify make COMMAND="cmd 2 run" on the command line'

all:
    ${COMMAND}

Now when you run make COMMAND="p2 Hi", you will get that command run and the appropriate output. If you forget to specify COMMAND="something or another" then you get an appropriate memory jogger.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278