makefilegnu-makemultiple-makefiles

How to dynamically rename an object file in a makefile


I am very very new to makefiles. The most complex task I had done before was to include new .h and and .cpp or .c in already designed makefiles.

I have to port the compilation process of a project from Visual Studio to gcc and there is an already made solution for this written by a colleague but he used 4 bash scripts and a makefile to compile the solution.

Instead of doing that I was looking for solutions to make it easier to maintain. My question may be very dumb I admit, but I could not find it anywhere nor I could understand it all properly.

In the target below:

$(OBJECTS): %.o: %.cpp 
    $(CC) $(CPPFLAGS) -c $< -o $@

I would like to test if the .o being created already exists and rename it to something else. This is necessary because in the project there are several source files that have the same name yet they are different in content.

For example, if the current .cpp being compiled is called file.cpp and the object that will be generated is file.o, the rule should test whether file.o already exists and rename the current file.o to something else.

If you know any good tutorial that explains this, please let me know. I found lots of examples that show how to make tests for the current file being compiled by that rule, but none that would rename the object .o.

Thanks in advance and sorry for any "dumbness" written here. :-)


Solution

  • First of all, you have our deep sympathy.

    Make is not really designed to handle such ambiguity, so we'll have to use a kludge. You haven't said what you want to rename the file to, so for now lets say we move file.o to file_save.o.

    # This tells Make that these are not real targets, so that it will
    # proceed even if file.o already exists.
    .PHONY: $(OBJECTS)
    
    $(OBJECTS): %.o: %.cpp 
        # If file.o exists, move it to file_save.o
        @if [ -f $@ ]; then mv $@ $*_save.o; fi
        $(CC) $(CPPFLAGS) -c $< -o $@