MacOS下使用Make工具时出现文件找不到问题求助
This issue boils down to a key difference between BSD Make (the default make on macOS) and GNU Make (used on Ubuntu) — how they handle the tilde (~) character in path variables. Here's what's happening and how to fix it:
Why This Happens
GNU Make (Ubuntu's default) automatically expands ~ to your user home directory when it appears in variables. But BSD Make (macOS' default) treats ~ as a literal part of the path. When your Makefile passes paths like ~/Documents/... to clang, BSD Make doesn't replace ~ with /Users/sduball, so clang looks for a directory literally named ~ (which doesn't exist) and throws the error.
Manual g++ commands work because your shell (bash/zsh) expands ~ before passing the path to the compiler — this expansion doesn't happen in BSD Make's variable handling.
The Fix
Replace all instances of ~ in your Makefile variables with $(HOME), which both BSD and GNU Make recognize as an environment variable that expands to your home directory. Here's your updated Makefile:
##### VARIABLES ##### CXX = g++ CXXFLAGS = -Wall -g -std=c++14 DIR = $(HOME)/Documents/Programming/Cpp/ncurses_projects/tictactoe/ SOURCE = $(HOME)/Documents/Programming/Cpp/ncurses_projects/tictactoe/source/ BUILD = $(HOME)/Documents/Programming/Cpp/ncurses_projects/tictactoe/build/ ##### TARGETS ##### # executable copy: main.o game.o $(CXX) $(CXXFLAGS) $(BUILD)main.o $(BUILD)game.o -lncursesw -o $(DIR)copy # source main.o: main.cpp game.h $(CXX) $(CXXFLAGS) -c $(SOURCE)main.cpp -o $(BUILD)main.o game.o: game.cpp game.h $(CXX) $(CXXFLAGS) -c $(SOURCE)game.cpp -o $(BUILD)game.o
Verify the Fix
- First, clean up any existing build artifacts (if you have a
cleantarget, runmake clean; otherwise, delete.ofiles in yourbuilddirectory). - Run
makeagain — the compiler should now find your source files correctly.
Alternative Option
If you prefer, you can also use the full absolute path (e.g., /Users/sduball/Documents/...) instead of $(HOME) — this will work across both macOS and Ubuntu without relying on variable expansion.
内容的提问来源于stack exchange,提问作者Spencer Duball

