当#include位于头文件时,Makefile编译无法找到SFML库文件
问题描述
我正在编写一个最小可复现示例,实现向SFML窗口输出“Applesauce”文本,涉及main.cpp、source.cc、header.hpp和Makefile四个自定义文件。当在header.hpp中包含<SFML/Graphics.hpp>时,执行mingw32-make编译会报错,提示找不到SFML/Graphics.hpp文件;但将该#include语句移至main.cpp时,程序可正常编译。我需要在header.hpp中包含该头文件,以便后续在.cc文件中编写依赖SFML库的函数,希望得到解决方法。
相关文件内容
main.cpp
#include "header.hpp" int main() { sf::RenderWindow window(sf::VideoMode(200, 200), "My window"); sf::Font font; font.loadFromFile("arial.ttf"); sf::Text text; text.setFont(font); text.setString(get_string()); text.setCharacterSize(24); text.setFillColor(sf::Color::Red); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(); window.draw(text); window.display(); } return 0; }
header.hpp
#ifndef HEADER_H #define HEADER_H #include <iostream> #include <SFML/Graphics.hpp> std::string get_string(); #endif // HEADER_H
source.cc
#include "../header.hpp" std::string get_string() { return "Applesauce"; }
Makefile
# Compiler CC=g++ # Flags for the C++ compiler CXXFLAGS=-Wall -Wextra -pedantic -std=c++17 # Include directory for SFML and the header files for your project INCLUDE=-Isrc -Isrc/include -Iscripts # Libraries to link against LIBS=-L src/lib -l sfml-graphics -l sfml-window -l sfml-system # List of source files SRCS=main.cpp scripts/source.cc # List of object files OBJS=$(patsubst %.cpp,%.o,$(SRCS)) # Executable file to create EXEC=applesauce all: $(EXEC) $(EXEC): $(OBJS) $(CC) $(OBJS) -o $(EXEC) $(LIBS) main.o: main.cpp $(CC) $(CXXFLAGS) $(INCLUDE) -c main.cpp -o main.o scripts/source.o: scripts/source.cc $(CC) $(CXXFLAGS) $(INCLUDE) -c scripts/source.cc -o scripts/source.o clean: rm -f $(EXEC) $(OBJS)
编译错误信息
PS C:\Users\[My Windows User Name]\Documents\C++ Visual Studio Projects\Headers and Scripts and SFML v4> mingw32-make g++ main.o scripts/source.cc -o applesauce -L src/lib -l sfml-graphics -l sfml-window -l sfml-system In file included from scripts/source.cc:1: scripts/../header.hpp:5:10: fatal error: SFML/Graphics.hpp: No such file or directory #include <SFML/Graphics.hpp> ^~~~~~~~~~~~~~~~~~~ compilation terminated. mingw32-make: *** [Makefile:25: applesauce] Error 1
错误原因
问题出在Makefile的OBJS变量生成规则上:
SRCS包含了.cpp和.cc两种后缀的文件,但patsubst %.cpp,%.o,$(SRCS)只会将.cpp后缀的文件转换为.o目标文件,source.cc因后缀是.cc不会被处理,导致OBJS中仅包含main.o。- 当Make执行链接步骤时,发现缺少
scripts/source.o,会调用默认编译规则处理scripts/source.cc,但默认规则不会使用你定义的CXXFLAGS和INCLUDE参数,导致编译时找不到SFML的头文件路径。
解决方法
修改Makefile中的OBJS变量,确保同时处理.cpp和.cc后缀的源文件,替换原有的OBJS行:
# List of object files OBJS=$(patsubst %.cpp,%.o,$(filter %.cpp,$(SRCS))) $(patsubst %.cc,%.o,$(filter %.cc,$(SRCS)))
或者更简洁的链式替换写法:
OBJS=$(SRCS:.cpp=.o) OBJS=$(OBJS:.cc=.o)
修改后重新执行mingw32-make,Make会按照你定义的规则编译scripts/source.cc,正确传递INCLUDE参数,从而找到SFML的头文件。
内容的提问来源于stack exchange,提问作者Game_Freeze
相关产品推荐
相关产品推荐

