Makefile,用于区分Windows和类Unix系统

Tom*_*rek 42 linux windows makefile os-detection

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

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


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

clean:
    del $(DESTDIR_TARGET)
Run Code Online (Sandbox Code Playgroud)

但在Linux上:

clean:
    rm $(DESTDIR_TARGET)
Run Code Online (Sandbox Code Playgroud)

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


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

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

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

Pau*_*son 42

我通过寻找一个只能在windows上设置的env变量来解决这个问题.

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/*)
Run Code Online (Sandbox Code Playgroud)

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

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

调用外部命令时,必须使用$(调用FixPath,path)(内部命令工作正常).您还可以使用以下内容:

/ := /
Run Code Online (Sandbox Code Playgroud)

然后

objs$(/)*
Run Code Online (Sandbox Code Playgroud)

如果你更喜欢那种格式

  • 谢谢你.我在Windows上的MinGW和Linux上的GCC之间切换,这很好用. (2认同)

tom*_*sgd 39

SystemRoot技巧在Windows XP上对我不起作用,但这样做:

ifeq ($(OS),Windows_NT)
    #Windows stuff
    ...
else
    #Linux stuff
    ....
endif
Run Code Online (Sandbox Code Playgroud)


Ant*_*sse 8

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