简体   繁体   English

Makefile目标需要其他目标的依赖性

[英]Makefile target requires dependency of other target

I have three c files and their header files: 我有三个c文件及其头文件:

  1. main/program.{c,h} 主程序/程序。{c,h}
  2. lib/lib1.{c,h} lib / lib1。{c,h}
  3. lib/lib2.{c,h} lib / lib2。{c,h}

program depends on lib1.o , which depends on lib2.o . program取决于lib1.o ,后者取决于lib2.o program does not directly depend on lib2.o . program不直接依赖lib2.o

program.main() calls lib1.func1() , which calls lib2.func2() . program.main()调用lib1.func1() ,后者调用lib2.func2()

I have two Makefile s; 我有两个Makefile one in the main folder, and another in lib. 一个在主文件夹中,另一个在lib中。

lib/Makefile: lib / Makefile:

all: lib1.o lib2.o

lib1.o: lib2.o lib2.h lib1.h

lib2.o: lib2.h

main/Makefile: 主文件/ Makefile:

VPATH=../lib

all: program

program: program.o lib1.o lib1.h
    $(CC) $(CFLAGS) -o $@ $^

When I run make -C main all , I get an undefined reference to 'func2' error. 当我运行make -C main all ,得到了undefined reference to 'func2'错误的undefined reference to 'func2' Both the lib object files compiled fine. 两个lib目标文件都可以正常编译。

Do I need to make lib2 a dependency of program even though it doesn't directly call it? 我是否需要使lib2成为program的依赖项,即使它没有直接调用它?

Yes. 是。 lib1.o contains a reference to a function that only exists in lib2.o. lib1.o包含对仅存在于lib2.o中的函数的引用。 If you don't tell the linker for main to also link against lib2.o it will never find it. 如果您不告诉main的链接器也链接到lib2.o,它将永远找不到它。 The compiler doesn't resolves the reference from lib1 to lib2 at compile time, it just checks the header to make sure it is being called correctly. 编译器在编译时不会解析从lib1到lib2的引用,它只是检查标头以确保正确调用了它。

You could have you lib directory Makefile build a .a (man ar) which includes both .o files, then link against the .a file from your main build. 您可以在lib目录Makefile中构建一个同时包含两个.o文件的.a(man ar),然后从您的主版本中链接该.a文件。

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

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