47

我希望在 Linux 和 Windows 上构建相同的 Makefile。我在 Linux 上 使用默认的GNU make ,在 Windows 上使用mingw32-make(也是GNU make)。

我希望 Makefile 检测它是在 Windows 还是 Linux 上运行。


例如make clean,Windows 上的命令如下所示:

clean:
    del $(DESTDIR_TARGET)

但在 Linux 上:

clean:
    rm $(DESTDIR_TARGET)

我还想在 Windows ( \) 和 Linux ( /) 上使用不同的目录分隔符。


可以在 Makefile 中检测 Windows 操作系统吗?

PS:我不想在 Windows 上模拟 Linux(cygwin 等)

有类似的问题:操作系统检测 makefile,但我没有在这里找到答案。

4

5 回答 5

51

我通过寻找一个只能在 Windows 上设置的环境变量来解决这个问题。

ifdef OS
   RM = del /Q
   FixPath = $(subst /,\,$1)
else
   ifeq ($(shell uname), Linux)
      RM = rm -f
      FixPath = $1
   endif
endif

clean:
    $(RM) $(call FixPath,objs/*)

因为 %OS% 是 windows 的类型,所以应该在所有 Windows 计算机上设置,而不是在 Linux 上。

然后,这些块为不同的程序设置变量以及将正斜杠转换为反斜杠的函数。

调用外部命令时必须使用 $(call FixPath,path) (内部命令工作正常)。你也可以使用类似的东西:

/ := /

接着

objs$(/)*

如果你更喜欢这种格式。

于 2010-12-22T16:15:35.110 回答
44

SystemRoot 技巧在 Windows XP 上对我不起作用,但确实如此:

ifeq ($(OS),Windows_NT)
    #Windows stuff
    ...
else
    #Linux stuff
    ....
endif
于 2011-06-16T12:19:51.183 回答
9

您可能应该使用 $(RM) 变量来删除一些文件。

于 2010-10-30T13:23:34.467 回答
2

我希望在 Linux 和 Windows 上构建相同的 Makefile。

也许你会喜欢CMake

于 2010-10-30T15:36:33.677 回答
1

检查 WINDIR 或 COMSPEC 区分大小写。相反,我想出了以下解决方案,希望有一天能对某人有所帮助:

# detect if running under unix by finding 'rm' in $PATH :
ifeq ($(wildcard $(addsuffix /rm,$(subst :, ,$(PATH)))),)
WINMODE=1
else
WINMODE=0
endif

ifeq ($(WINMODE),1)
# native windows setup :
UNLINK = del $(subst /,\,$(1))
CAT = type $(subst /,\,$(1))
else
# cross-compile setup :
UNLINK = $(RM) $(1)
CAT = cat $(1)
endif
于 2018-08-25T10:58:12.100 回答