问题描述
我正在为我的程序设计一个makefile,该程序运行一个简单的文本编辑程序,并为命令行参数获取一个文件.但是,我遇到的问题是,当我尝试在makefile中传递命令行参数时,编译器似乎没有意识到该文件,或者给出了某种错误以指示链接出错.我的makefile源代码如下所示:
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:
1 all: basic.c
2 gcc -o basic2 basic2.c data
3 write: basic2.o
4 gcc -o basic2 basic2.o
5 basic2.o: basic2.c
6 gcc basic2.c data
及其结果输出:
Must name an input file
如果在运行basic2.c时不带任何参数(例如数据)的情况,这是程序应打印的内容.我应该将参数移到另一行,还是有更好的方法编写此代码?
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?
作为参考,basic2.c使用以下代码:
Also, for reference, basic2.c uses the following code:
main(int argc, char *argv[])
7 {
8 if(argc > 2) {
9 printf("Too many file names\n");
10 exit(0);
11 }
12 if(argc != 2) {
13 printf("Must name a file\n");
14 exit(0);
15 }
我引用的argv索引错误吗?
Am I referencing the wrong index of argv?
推荐答案
您似乎在尝试在第三个 make
运行 basic2
>块.如果您打算让第一个make目标同时编译并运行,那么您可能打算这样做:
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
然后,使用命令 make
将构建 basic2
(如果已更改),然后运行代码.
Then, using the command make
will build basic2
if it has changed, and then run the code.
make write
命令的作用与 make
相同.
如果需要,将仅编译命令 make basic2
.
The command make basic2
will just compile if necessary.
当然,在这种情况下,不需要 all:write
,但是如果您要构建其他东西,则在 write
之后添加更多的依赖项将很有用.代码>.
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
.
这篇关于通过Makefile的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!