I have some code that is "optional": the rest of the program can be linked without it.
How do I properly create a Makefile that excludes it as a dependency if there is an error when creating the object file?
So far I have something like this:
OUT=my_program
OBJS=$(subst .cc,.o,$(wildcard *.cc))
all: $(OUT)
$(OUT): $(OBJS)
my_optional_file.o: other_target
.IGNORE: my_optional_file.o
The good: When processing the rule my_optional_file.o, this correctly ignores all errors.
The bad: When linking the output, my_optional_file.o is specified as an argument to the linker despite the fact that it was not built, making the linker fail because it was given a nonexistent file as input!
How do I exclude my_optional_file.o when there is an error in building it?
Use $(shell find . -maxdepth 1 -iname "*.o") with an explicit call to the linker.
Like :
$(OUT): $(OBJS)
$(CXX) $(LDFLAGS) $(shell find . -maxdepth 1 -iname "*.o") $(LDLIBS) -o $@
The reason is that when implicitly called, the linker command is called like this :
$(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@
With $^ expanding to the content of $(OBJS). You need an explicit call to use specific files instead.
The $(wildcard *.o) function cannot be used because it is executed before the files are created so it is always empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With