如何在macOS上使用Makefile?

How to use Makefile on macOS?

本文关键字:Makefile macOS      更新时间:2023-10-16

在macOS上,如果我用

clang -I. -framework OpenGL main.cpp glad.c /usr/local/Cellar/glfw/3.3.1/lib/libglfw.3.3.dylib

我可以从以下代码构建并运行生成的可执行文件:

#define GL_SILENCE_DEPRECATION
#include <stdio.h>
#include "glad/glad.h"
#include "/usr/local/Cellar/glfw/3.3.1/include/GLFW/glfw3.h"
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClearColor(0.9, 0.1, 0.1, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}

但是我想使用 Makefile 进行构建,所以我准备了

CC         = clang
XXFLAGS    = -g -Wall -v
CPPFLAGS   = -I.
LDLIBS     = -lm -L/usr/local/Cellar/glfw/3.3.1/lib -lglfw
LDFLAGS    = -framework OpenGL
OBJS       = main.o glad.o 
PROGRAM    = main
$(PROGRAM): $(OBJS)
$(CXX) $^ $(XXFLAGS) $(CPPFLAGS) $(LDLIBS) $(LDFLAGS) -o $@
clean:
-rm -f *.o
distclean: clean
-rm -Rf $(PROGRAM) 

它实际上使可执行文件,但是当我运行它时,我得到

$ ./main 
Segmentation fault: 11

所以我想 Makefile 有问题,对吧?

$ make -n
c++  -I.  -c -o main.o main.cpp
clang  -I.  -c -o glad.o glad.c
c++ main.o glad.o -g -Wall -v -I. -lm -L/usr/local/Cellar/glfw/3.3.1/lib -lglfw -framework OpenGL -o main

您没有定义规则来构建OBSJ,因此make使用了其内置规则。PROGRAM规则仅链接对象文件,没有必要在那里指定CPPFLAGS

.PHONNY: all
all: clean a.out
a.out:
clang++ -I glad/include -F /Library/frameworks -framework OpenGL main.cpp glad/src/glad.c /usr/local/Cellar/glfw/3.3.1/lib/libglfw.3.3.dylib
clean:
rm a.out

引用:

  • https://www.gnu.org/software/make/manual/make.html
  • https://opensource.com/article/18/8/what-how-makefile