0

I'm using Ubuntu Linux and g++ as compiler / linker.

Sources are located in "./src"

Headers are located in "./include"

I want to make to recompile a given *.o file if (and only if) the corresponding CPP source file or header file has changed. Unless I run "make clean", of course, in which case it should recompile everything. How do I do this?

Below is the relevant part of my makefile:

NAME                = ext

INI_DIR             =   /etc/php/7.4/cli/conf.d

EXTENSION_DIR       =   $(shell php-config --extension-dir)
DIST_DIR        =   ./dist

EXTENSION           =   dist/${NAME}.so
INI                 =   ${NAME}.ini

COMPILER            =   g++
LINKER              =   g++

SOURCES             =   $(wildcard src/*.cpp)
OBJECTS             =   $(SOURCES:%.cpp=%.o)


all:                    ${OBJECTS} ${EXTENSION}

${EXTENSION}:           ${OBJECTS}
                        ${LINKER} ${LINKER_FLAGS} -o $@ ${OBJECTS} ${LINKER_DEPENDENCIES}

${OBJECTS}:
                        ${COMPILER} ${COMPILER_FLAGS} $@ ${@:%.o=%.cpp}

install:        
                        ${CP} ${EXTENSION} ${EXTENSION_DIR}
                        ${CP} ${INI} ${INI_DIR}

dist:       
                        ${CP} ${EXTENSION} ${DIST_DIR}
                
clean:
                        ${RM} ${EXTENSION} ${OBJECTS}

EDIT:

I added this to the makefile

DEPS                =   $(wildcard $(OBJECTS:%.o=%.d))
    
include $(DEPS)

....

clean:
                        ${RM} ${EXTENSION} ${OBJECTS} ${DEPS}

And I added to -MM to compiler flags.

Now the compiler command looks like this:

g++ -MM -Wall -I/some/path/lib -I/other/path/lib2 -c -O2 -std=c++17 -fpic -o src/islide_collection.o src/islide_collection.cpp

This creates the dependency files now, but the *.o files are all empty, so the linker returns an error.

What's wrong?

Btw: this is NOT only about header file changes. I want make to recompile x.o when either x.cpp or x.h are modified.

user2297996
  • 1,382
  • 3
  • 18
  • 28
  • yes its possible, its quite complex, simplest solution is to use something like cmake that does the work for you – Alan Birtles Nov 27 '20 at 14:20
  • Did you consider using [ninja](http://ninja-build.org/) or [omake](http://omake.metaprl.org/index.html) ? Did you read documentation on [Invoking GCC](https://gcc.gnu.org/onlinedocs/gcc/Invoking-GCC.html) - e.g. the `-M` options – Basile Starynkevitch Nov 27 '20 at 14:29
  • 1
    Yes, what you’ve described is exactly what `make` is designed for. – Pete Becker Nov 27 '20 at 14:38

0 Answers0