I'm designing a makefile for a program of mine that runs a simple text-editing program and takes in a file for a command-line argument. The issue I'm running into, though, is that when I try to pass in a command line parameter in the makefile, the compiler either doesn't seem to acknowledge the file or gives some kind of error to indicate the linking went wrong. My source code for the makefile looks something like this:
all: basic.c
gcc -o basic2 basic2.c data
write: basic2.o
gcc -o basic2 basic2.o
basic2.o: basic2.c
gcc basic2.c data
and the resulting output:
Must name an input file
This is what the program should print out if basic2.c is run without an argument, such as data. Should I move the parameter to a different line, or is there a better way to write out this code?
Also, for reference, basic2.c uses the following code:
main(int argc, char *argv[])
{
if(argc > 2) {
printf("Too many file names\n");
exit(0);
}
if(argc != 2) {
printf("Must name a file\n");
exit(0);
}
}
Am I referencing the wrong index of argv?
It looks like you are trying to run basic2
in your third make
block. If your intent was to have the first make target do both compile and run, you probably meant to do this:
# All depends on write, which depends on basic2, which depends on basic2.c
all: write
# Command to run
write: basic2
./basic2 data
# Command to compile
basic2: basic2.c
gcc -o basic2 basic2.o
Then, using the command make
will build basic2
if it has changed, and then run the code.
The command make write
will do the same as just make
.
The command make basic2
will just compile if necessary.
Of course, all: write
is not necessary in this case, but if you have other things you want to build together, it would be useful to add more dependencies after write
.