Is there a way to set '-lm' as the default for GCC?


Background: I originally learned C using Turbo C on DOS 6, in 1990; there were a lot of things that Turbo C treated as standard that apparently weren’t (even then).

Now I’m refreshing myself by working through "88 C Programs". I’ve discovered that when I need to use functions from math.h on GCC (like sqrt(), log10(), etc.), I have to manually link the math libraries by appending -lm at the end of the GCC command. Is there a way to automate this action (say, with an environment variable), so that, if I have #include "math.h" I automatically get -lm added to the compile command and don’t have to remember to type it?

As a single user on a quad-core CPU, I’m not terrifically concerned about tiny performance differences.

Potentially significant: I’m using the version of GCC and its dependencies found in the Ubuntu repositories, on Kubuntu 14.04.

Is there a way to set -lm as default for GCC?


If you’re using Bash (or some other Bourne-derived shell), you can define a shell function. For example:

gccm() { gcc "[email protected]" -lm; }

An alias won’t do the job, since the -lm argument has to follow the name of the source or object file that depends on the math library. (The -lm argument is passed to the linker, which keeps track of unresolved references for each file; those unresolved references may be resolved by later arguments.)

(C shell (csh) aliases are a little more powerful than Bash aliases—but C shell doesn’t have shell functions.)

Note that this function requires you to use a different command name. If you want to type gcc and have it invoke the gcc command with an added argument, you need to do a little extra work to avoid having the function invoke itself:

gcc() { command gcc "[email protected]" -lm; }


gcc() { /usr/bin/gcc "[email protected]" -lm; }

command is a Bash built-in that invokes a specified command while bypassing any shell function with the same name. Or you can specify the full path to gcc.

Creating a function like this also gives you an opportunity to add more default arguments. gcc’s default mode is rather lax, and it supports the "gnu90" dialect of the language (C89 with GNU-specific extensions). You can specify additional arguments to recognize a more modern version of the language and to perform more compile-time checks:

gcc() { command gcc -std=c99 -pedantic -Wall -Wextra "[email protected]" -lm; }

Another alternative is to write a wrapper script and put it in a directory ahead of /usr/bin in your $PATH, for example $HOME/bin.

(Some commands recognize environment variables that implicitly add command-line options; for example GNU grep recognizes $GREP_OPTIONS. gcc does not.)

Answered By – Keith Thompson

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published