简体   繁体   English

如何用-S和-c编写makefile来编译?

[英]How to write makefile to compile with -S and -c?

I have a source file test.c and its header test.h , a file main.c and the makefile . 我有一个源文件test.c和它的头test.h ,一个文件main.cmakefile I want to set up my makefile so that it (1) compiles test.c to build an executable test.o , and (2) compiles test.c to print the assembly code to test.s using -S flag. 我想设置我的makefile,以便它(1)编译test.c以构建可执行的test.o ,并且(2)编译test.c以使用-S标志将汇编代码打印到test.s

I have tried to set up the makefile as I thought would be correct, but this of course doesn't actually run the last test.s line. 我试图设置makefile,因为我认为是正确的,但这当然不会运行最后一个test.s行。

FLAGS = -c -Wall
CC = gcc
ASM = -S

all : optimize
optimize: main.o test.o
    $(CC) main.o test.o -o optimize
main.o: main.c test.h
    $(CC) $(FLAGS) main.c
test.o: test.h test.c
    $(CC) $(FLAGS) test.c
test.s: test.h test.c
    $(CC) $(ASM) -Wall test.c

Can anyone tell me how I should have structured this differently, to create both test.s and test.o? 谁能告诉我如何我应该有这种不同的结构, 同时创建test.s和test.o?

I tried to change the optimize: line and the following one to: 我尝试将optimize: line和以下内容更改为:

optimize: main.o test.o test.s
    $(CC) main.o test.o test.s -o optimize

but the linker gave an error multiple definition of 'test' . 但是链接器错误地multiple definition of 'test'

Simply add test.s to the line that starts with optimize: . 只需将test.s添加到以optimize:开头的行。

What this does is add the rule test.s to the dependencies of the optimize line. 这样做是将规则test.s添加到优化行的依赖项中。

You could also add it to the all line, as suggested by Vaughn Cato. 您也可以按照Vaughn Cato的建议将其添加到所有行。

It's important to know that there is a difference between the rule test.s and the file test.s 重要的是要知道规则test.s和文件test.s之间存在差异

You can put anything you want as the name of the rule, but by convention you normally just use the filename. 您可以将任何您想要的内容作为规则的名称,但按照惯例,您通常只使用文件名。

Here's an example Makefile that will do what you want. 这是一个可以做你想做的Makefile的例子。 I put the dep under all so you can just make asm and I also changed the rule name to asm for clarity. 我把dep放在所有,所以你可以make asm ,我也将规则名称更改为asm以保持清晰。

FLAGS = -c -Wall
CC = gcc
ASM = -S

all : optimize asm
optimize: main.o test.o
    $(CC) main.o test.o -o optimize
main.o: main.c test.h
    $(CC) $(FLAGS) main.c
test.o: test.h test.c
    $(CC) $(FLAGS) test.c
asm: test.h test.c
    $(CC) $(ASM) -Wall test.c -o test.s

Finally, because you seem a bit shaky on how Makefiles work, (I don't blame you honestly), I suggest reading this tutorial: http://mrbook.org/tutorials/make/ 最后,因为你对Makefiles的工作方式看起来有点不稳定(我不诚实地责怪你),我建议你阅读这个教程: http//mrbook.org/tutorials/make/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM