makefile with dependency on a shared library sub project

我怕爱的太早我们不能终老 提交于 2021-02-11 12:38:10

问题


So I have a makefile. I'll just put a pseudo example for the moment just enough so that I can talk about the issue and keep it simple...

Let's say I have in my makefile something like this:

# Rule to build my test executable - with dependency on the library mytest
build: libmytest.so
    g++ test.cpp -lmytest.so

# Rule to build mytest library
libmytest.so:
    g++ mytestlib.cpp -fPIC   ... etc ...
    cc -fPIC -Wl,-soname,libmytest.so  ... etc...

So, if/when I change the file mytestlib.cpp, I see that since mylibtest.so already exists (from a previous build) my build rule thinks it has nothing to do.

So my question is how can I get the library to build and therefore test.cpp to relink to the newly create library, if I change only the library file?


回答1:


This is exactly what make is made for: manage a dependency tree. Just tell make that your library depends on its sources:

libmytest.so: mytestlib.cpp
    g++ mytestlib.cpp -fPIC   ... etc ...
    cc -fPIC -Wl,-soname,libmytest.so  ... etc...

With this extra piece of information make will compare the last modification times of the target and its prerequisites. If the target is missing or older than any of its prerequisites, make will rebuild it. And this is recursive. If a prerequisite is missing or itself out of date with respect to its own prerequisites, make will rebuild it first.

By the way, instead of a build target, which is not the name of a real file, it would be better to use directly the file name of the product:

test: libmytest.so
    g++ test.cpp -lmytest.so

This way, if test is up to date (more recent than libmytest.so) make will not rebuild it. You will save time.

If you really want an alias for this, you can add a phony target:

.PHONY: build

build: test

All prerequisites of the special .PHONY target are treated differently: make knows that they are not real file names, even if a file named build exists, and that they must always be rebuilt. In this case, make will check that test exists and is up to date, rebuild test if needed, and stop here because there is nothing to do for build (it has no recipe). You can thus consider it as a kind of alias for test.



来源:https://stackoverflow.com/questions/51653483/makefile-with-dependency-on-a-shared-library-sub-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!