简体   繁体   中英

How to use Makefile on macOS?

On macOS, if I compile with

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

I can build and run the generated executable from the following code:

#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;
}

But I would like to build using a Makefile, so I prepared

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) 

It actually makes the executable but when I run it I get

$ ./main 
Segmentation fault: 11

So I guess there is something wrong in the Makefile, right?

$ 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

You didn't define the rule to build OBSJ , so make used its built-in rules. The PROGRAM rule only links object files, and there's no point specifying CPPFLAGS there.

.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

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM