开发者

How to dynamically rename an object file in a makefile

开发者 https://www.devze.com 2023-03-01 02:10 出处:网络
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 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 so开发者_开发知识库lution 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. :-)


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 $@


Expansion of my comment on the question:

Perhaps you should consider placing object files in the same directory hieryarchy as the source files, to prevent naming conflicts.

So that src/network/client.cpp is compiled to build/obj/network/client.o.

I'm extremely rusty when it comes to makefiles but I believe I solved that by doing something like:

$SRC= src/network/client.cpp src/main.cpp .....
$OBJ= makefile_replace_function($SRC, .o)

$(OBJ) : $(SRC)
   compile_instructions

Where you will have to replace makefile_replace_function and compile_instructions to their real equivalents since I have forgotten then...

I realize this might not be very helpful but atleast its an idea to consider.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号