DEV Community

loading...

Makefile "origin" function explained

nevergarden profile image Nevergarden ・2 min read

Origin Function

On my very first days using Linux, Some magical chain of commands were in documentation of every software I wanted to use (since I liked the build from source concept). Those magical commands were:

./configure
make
make install
Enter fullscreen mode Exit fullscreen mode

And now when I read make files I still learn new things. Today I saw a great function: origin.
origin function is explained in GNU documentation, but here I provide some examples of their usage.

In Makefile if you call $(origin Variable) there make file will evaluate it into undefined, default, environment environment override, file, command line, override and automatic. here I will explain how to use them all:

undefined

This one is so simple just write a Makefile knowing that VARIABLE_NERVER_DEFINED is not defined and echo it.

echo $(origin VARIABLE_NEVER_DEFINED)
Enter fullscreen mode Exit fullscreen mode

default

There are some variables which are defined by make and used by it like CC.
so when you ask where their origin is he would tell you default:

A make file with default output:

echo $(origin CC)
Enter fullscreen mode Exit fullscreen mode

These variables are listed here: Variables

environment

When an environment variable is defined even if it's CC, when you call origin it will return environment:

echo $(origin VAR)
Enter fullscreen mode Exit fullscreen mode

called from command line as:
$ VAR=hello make or it was set before like PWD in most of systems.

$ export PWD=$(pwd)
$ cat echo $(origin PWD) > Makefile
$ make
echo environment
environment
Enter fullscreen mode Exit fullscreen mode

environment override

If you call make with -e flag when you override a Makefile Variable like CC, it shall tell you that environment has override that variable:

$ CC=gcc make -e
echo environment override
environment override
Enter fullscreen mode Exit fullscreen mode

file

If you defined a variable inside your Makefile:

CC=gcc

echo $(origin CC)
Enter fullscreen mode Exit fullscreen mode

will evaluate into:
echo file
file

command line

This one is so useful, I saw this in kernel code so I started searching for what is origin function:

echo $(origin VAR)
Enter fullscreen mode Exit fullscreen mode

When you set that VAR after you call make:
make VAR=hello
will evaluate into:
command line

override

Done shown when a variable is overridden here's an example:

override CFLAGS += -Wall
echo $(origin CFLAGS)
Enter fullscreen mode Exit fullscreen mode

automatic

I couldn't find how it works... I would update if anyone knows and provides an example.

Discussion (0)

pic
Editor guide