Home > Enterprise >  What's the difference between having a library as a dependency in a makefile vs without the dep
What's the difference between having a library as a dependency in a makefile vs without the dep

Time:04-20

I'm quite new to makefiles, and I'm wondering what exactly is the role of the library in this format:

app: app.o mylibrary.a
$(LD) -o $@ $(LDFLAGS) app.o mylibrary.a

What I usually see would be something like this:

app: app.o
$(LD) -o app $(LDFLAGS) $^ mylibrary.a

My understanding for this format is that the executable will be made from the app.o file, which has a dependency on mylibrary.a.

I can't quite understand the difference/meaning of the first version though.

CodePudding user response:

Where the $@ is the target is substituted, in the first case that would be app.

Although they aren't defined in the question, the $(LD) and $(CFLAGS) are usually defined as the c-compiler and the flags to use in the compiler. E.g. something like CFLAGS = -g -Wall -std=c99 -lstdc would be a defined line at the top of the Makefile. I'd usually write these as the first two parts of the command to run for the target.

The $^ indicates to substitute everything that is listed as a dependency of the target. In the first row the dependencies are app.o mylibrary.a whereas in the second it is only app.o. These ($^, $@)are usually used to simplify the writing of make rules. The choice of whether to use the wildcards-as these are called-is really your own choice. I usually use them because they make it easier to write and maintain.

So to answer your question the main difference is where you explicitly need to place the name of the file.

Additional note on dependencies The files in the line where there are dependencies of the target listed are used by make to determine which targets need to be rerun. Make does a topological sort of the dependencies and if something changes-based on last touched time of file-the make command will rerun the target if it is within the path of the make target that is being called.

  • Related