64

How can I make GNU Make use a different compiler without manually editing the makefile?

Clark Gaebel
  • 17,280
  • 20
  • 66
  • 93

6 Answers6

94

You should be able to do something like this:

make CC=my_compiler

This is assuming whoever wrote the Makefile used the variable CC.

jonescb
  • 22,013
  • 7
  • 46
  • 42
  • 2
    Commonly used variables are `CC`, `GCC`, `CCX`, etc... but, as stated, one has to read the `Makefile` to see what variable(s) are used (and also if it's C++ or C). Just came across this answer while using a Makefile that has a check if you're using `GCC` (eg, `make GCC=gcc-6`) and prints an error message asking to instead use `HOST_COMPILER` (e.g., `make HOST_COMPILER=g++-6` vs my default of `g++` , which is newer v7) (fyi it's the Nvidia CUDA samples). – michael Sep 19 '18 at 02:52
  • 1
    this is a terrible answer, it does not cover what is supposed to go in "my compiler" – TheNegative Jul 30 '19 at 15:20
29

You can set the environment variables CC and CXX, which are used for compiling C and C++ files respectively. By default they use the values cc and g++

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • 2
    If the makefile was written to use CC and CCX –  Jun 03 '10 at 19:50
  • 6
    Setting environment doesn't override explicit values in a makefile unless you use '-e' to tell make to let it do so. It does override defaults, though - and most likely the defaults are used. – Jonathan Leffler Jun 03 '10 at 19:52
21

If the makefile is written like most makefiles, then it uses $(CC) when it wishes to invoke the C compiler. That's what the built-in rules do, anyway. If you specify a different value for that variable, then Make will use that instead. You can provide a new value on the command line:

make CC=/usr/bin/special-cc

You can also specify that when you run configure:

./configure CC=/usr/bin/special-cc

The configuration script will incorporate the new CC value into the makefile that it generates, so you don't need to manually edit it, and you can just run make by itself thereafter (instead of giving the custom CC value on the command line every time).

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
11

Many makefiles use 'CC' to define the compiler. If yours does, you can override that variable with

make CC='/usr/bin/gcc'
ladenedge
  • 13,197
  • 11
  • 60
  • 117
1

Use variables for the compiler program name.
Either pass the new definition to the make utility or set them in the environment before building.

See Using Variables in Make

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

Makefile:

#!MAKE

suf=$(suffix $(src))
ifeq ($(suf), .c)
cc=gcc
else
ifeq ($(suf), .cpp)
cc=g++
endif
endif

all:
    $(cc) $(src) -o $(src:$(suf)=.exe)

clean:
    rm *.exe

.PHONY: all clean

Terminal:

$ make src=main.c
Multifix
  • 131
  • 1
  • 8