Вы могли дать некоторый признак того, для каких платформ Вы пишете? Это должно лечь тяжелым бременем на то, что является 'лучшим'. Вы могли бы найти супер библиотеку 'xml-нечто', которая обычно не поставлется в большинстве систем по умолчанию.. в то время как его великое, отсутствие библиотеки могло бы предотвратить (или по крайней мере) раздражают пользователей.
Главным образом, я использую libxml2.. потому что его стандартное или легкое для установки на платформах, для которых я нацелен.
, Как Вы видите, 'лучше всего' также определяется библиотекой, являющейся доступным на Ваших целевых платформах.
РЕДАКТИРОВАТЬ:
Я пробовал ваш make-файл, и этот оператор sed, похоже, отлично удаляет конечные обратные косые черты. Попробуйте что-нибудь попроще, например:
backslash: @echo " \\" > $@ test: backslash @echo without sed: @cat backslash @echo with sed: @sed -e 's/ *\\$$//' < backslash
РЕДАКТИРОВАТЬ:
Хорошо, теперь я на крючке. Не могли бы вы попробовать эти эксперименты и рассказать нам о результатах?
Change the last character to 'z' : s/.$/z/ Change a trailing backslash to 'z' : s/\\$/z/ Change a trailing backslash to 'z' : sm\\$mzm Delete a trailing backslash : s/\\$// Delete spaces and a trailing backslash: s/ *\\$// Try all of these inside and outside of Make, with '$' and '$$'.
Вы можете использовать qmake для создания Make-файлов для проекта, даже если этот проект не использует Qt.
В системе сборки Mozilla мы используем переключатель GCC -MD для создания файлов зависимостей: http://mxr.mozilla.org/mozilla-central/source/configure.in#7134 а затем мы используем сценарий с именем mddepend.pl для проверки удаленных файлов заголовков, чтобы удаление заголовка просто вызывает перестройку, а не ошибку: http://mxr.mozilla.org/mozilla-central/source/config/rules.mk#2066 http://mxr.mozilla.org/mozilla-central/source/build/unix/mddepend .pl
Этот сценарий генерирует файл .all.pp, содержащий все зависимости, с добавлением дополнительных foo.o: FORCE
зависимостей для отсутствующих файлов заголовков. Затем мы просто -включаем файл .all.pp в rules.mk прямо под ним.
Я использую BSD make (pmake?), Которая выполняет для меня много работы (мой язык - C, но я думаю, здесь нет никакой разницы). Это мой общий 'local.prog.mk', я никогда его не меняю:
.PHONY: tags .depend
# .depend depends only on $(SRCS) in bsd.dep.mk, so we can't track changes of
# header's own dependencies properly. so .depend is .PHONY target here.
CSTD ?=c99
WARNS ?=9
.if !empty(PC_LIST)
PC_CF !=pkg-config --cflags $(PC_LIST)
PC_LD !=pkg-config --libs $(PC_LIST)
.endif
CFLAGS +=$(PC_CF) -fgnu89-inline
.if !defined(NO_DEBUG)
CFLAGS +=-O0 -ggdb3
.endif
LDFLAGS +=$(PC_LD)
CTAGS =exctags
NO_MAN=
NO_OBJ=
CLEANFILES+=$(PROG).core
.include <bsd.prog.mk>
$(PROG): $(SUBDIR)
build: clean cleandepend depend all
run: $(PROG)
./$(PROG)
Обратите внимание на включение 'bsd.prog.mk' - он обрабатывает все, строит, зависит, чистые цели. Специфичные для проекта BSDmakefile
просты:
.SILENT:
PROG =hello
SRCS =hello.c world.c
PC_LIST =gtk+-2.0 gnet-2.0
.include "../local.prog.mk"
proto:
cproto -siv `pkg-config --cflags $(PC_LIST)` $(SRCS) > prototypes
CLEANFILES+=prototypes
Я просто делаю зависимость каждый раз, когда вставляю / удаляю любые директивы #include.
I must be missing something. Why doesn't generating dependency files work for you?
Я предпочитаю использовать CMake, хотя это не совсем решение вашей проблемы.
Это язык описания проекта, который генерирует ваши файлы Makefile, проект Visual Studio, проект Eclipse, KDevelop и т. д. для вас. Все зависимости сделаны за вас:
CMakeLists.txt
add_executable(my_exe file1.c file2.c)
target_link_libraries(my_exe my_library)
add_subdirectory(lib)
В lib / CMakeLists.txt
add_library(my_library file3.c file4.c)
Это создает my_exe из file1.c file2.c, связанного с my_library. Я считаю, что это намного проще. В нем также есть такие вещи, как обнаружение пакетов:
find_package(Qt4)
В make-файле все, что вы указываете в строке зависимости, является заголовочными файлами зависимости или другими включенными файлами.
Учебник BSD по make Примечание: вы можете автоматически сгенерировать информация о зависимости заголовка с ключом -MM GCC.
gcc/g++ can generate dependencies for you with the -M
family of options.
The following works by specifying how to generate .depends
files given a source file. By doing -include $(DEPS)
$(DEPS) is recognized as a target and will be built/rebuilt when the source files change.
CXX = g++
CXXFLAGS = -Wall -O3
LDFLAGS =
TARGET = testcpp
SRCS = main.cc x.cc foo.cc
OBJS = $(SRCS:.cc=.o)
DEPS = $(SRCS:.cc=.depends)
.PHONY: clean all
all: $(TARGET)
$(TARGET): $(OBJS)
$(CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJS) -o $(TARGET)
.cc.o:
$(CXX) $(CXXFLAGS) -c $< -o $@
%.depends: %.cc
$(CXX) -M $(CXXFLAGS) $< > $@
clean:
rm -f $(OBJS) $(DEPS) $(TARGET)
-include $(DEPS)
The makedepend utility is installed on many systems and can be quite useful for generating dependency information.
Here is an example Makefile that uses the include
directive (plus a little Perl magic) to incorporate the output from makedepend:
# the name of the executable that we'll build
TARGET = foo_prog
# our .cc source files
SRCS = foo.cc main.cc
# the .o versions of our source files
OBJS := $(patsubst %.cc, %.o, $(filter %.cc, $(SRCS)))
# some flags for compiling
CXXFLAGS = -Wall -Werror
# In order to build $(TARGET), we first build each of the $(OBJS).
# Then we use the given command to link those $(OBJS) into our
# $(TARGET) executable. $^ is a shortcut for $(OBJS). $@ is a
# shortcut for $(TARGET).
#
# The default compile rule will compile each of the $(OBJS) for us.
$(TARGET): $(OBJS)
$(CXX) $(CXXFLAGS) $^ -o $@
# Use "make clean" to remove all of the support files.
clean:
rm -f $(OBJS) $(TARGET) Makefile.depend *~
# This automatically uses the 'makedepend' utility to add any
# dependencies that our source files have, namely .h files. This way,
# if the .h files change, the code will be re-compiled.
include Makefile.depend
Makefile.depend: $(SRCS)
makedepend -f- -Y $(SRCS) 2> /dev/null | \
perl -p -e "s/(^.*?:)/Makefile.depend \1/" > Makefile.depend
If both foo.cc
and main.cc
depend on foo.h
, then the contents of Makefile.depend
would be:
Makefile.depend foo.o: foo.h
Makefile.depend main.o: foo.h
The end result is that the dependency information from makedepend
is injected into the Makefile as a series of rules. It's similar to the approach of using a .d
file for each .cc
file, but keeps the dependency information in one file instead of scattered all over the place.