LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 802|回复: 1

典型的源码目录组织结构编译Makefile失败。

[复制链接]
发表于 2006-5-11 12:03:07 | 显示全部楼层 |阅读模式
一个简单的Demo演示源程序
  1. [root@root Make]# ls
  2. include  main.cpp  Makefile  README  src
  3. [root@root Make]# less include/hello.h
  4. #ifndef _HELLO_H
  5. #define _HELLO_H
  6. void Display(char *);
  7. #endif
  8. [root@root Make]# less src/hello.cpp
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <include/hello.h>
  12. void Display(char *pChar)
  13. {
  14.     fprintf(stdout, "%s\n", pChar);
  15.     return;
  16. }
  17. [root@root Make]# less main.cpp
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <include/hello.h>
  21. int main(int argc, char *argv[])
  22. {
  23.     Display(argv[1]);
  24.     return 1;
  25. }
复制代码
Makefile的结构
  1. [root@root Make]# less Makefile
  2. # Compiler.
  3. CC     = gcc
  4. CCPLUS = g++
  5. BASEDIR= ./
  6. SRCS   =$(BASEDIR)main.cpp \
  7.         $(BASEDIR)/src/hello.cpp
  8. OBJS   =$(BASEDIR)main.o \
  9.         $(BASEDIR)/src/hello.o
  10. # Compilers options for tool.
  11. CFLAGS = -Wall -g  
  12. INCS   = -I.
  13. 第一种写法:编译失败,为什么?
  14. $(OBJS) : $(SRCS)
  15.         $(CCPLUS) $(CFLAGS) $(INCS) -c $^ -o $@
  16. 第二种写法:只能编译前一个main.cpp, src/hello.cpp不能编译,为什么?
  17. $(BASEDIR)main.o : $(BASEDIR)main.cpp
  18.         $(CCPLUS) $(CFLAGS) $(INCS) -c $< -o $@
  19. $(BASEDIR)/src/hello.o : $(BASEDIR)/src/hello.cpp
  20.         $(CCPLUS) $(CFLAGS) $(INCS) -c $< -o $@
  21. demo: $(OBJS)
  22.         $(CCPLUS)   -o $@  $^
  23. all: demo
  24. .PHONY: clean
  25. clean:
  26.         rm $(OBJS)
  27.         rm demo
复制代码
目的:是想通过Makefile,在当前目录下生成main.o,在src/下生成hello.o, 然后又在当前目录下生成ELF的demo。如果用make的implicit rules时,改一下他们的头文件路径就可以编译通过。用自己的rules,始终没过。
发表于 2006-5-11 14:02:05 | 显示全部楼层
第一种不行是因为每个规则只能用于编译一个源文件。你这样一大堆写进去显然不对。
第二种不行是因为hello.h文件不在默认搜索路径下。你应该手动将.h文件的路径也写上。

建议看看GNU Make文档,这些就不是问题了。如果学习autotools,用自动化工具生成configure脚本和Makefile会更方便。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表