因此,我试图创建一个自定义头文件,其中包含我对几个图形函数(如drawPixel、drawLine等)的实现。我的源文件(带有主函数)和头文件都包含SFML库。当我在源文件中使用 sfml 函数时,它运行没有错误,但是当我在头文件中使用相同的函数时,它显示“链接器命令失败”。
sfml.cpp(源文件)
#include<SFML/Graphics.hpp>
#include "my_graphics.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(500, 500), "SFML works!");
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
// Clear the window
window.clear();
putPixel(window,100,100);
window.display();
}
return 0;
}
my_graohics.h
#ifndef MY_GRAPHICS_H
#define MY_GRAPHICS_H
#include <SFML/Graphics.hpp>
void putPixel(sf::RenderTarget& target, int x, int y);
#endif
my_graphics.cpp
#include "my_graphics.h"
void putPixel(sf::RenderTarget& target, int x, int y) {
sf::Vertex vertex;
vertex.position = sf::Vector2f(x, y);
vertex.color = sf::Color::White;
sf::VertexArray point(sf::Points, 1);
point[0] = vertex;
target.draw(point);
}
构建命令
clang++ -std=gnu++14 -std=c++17 -fcolor-diagnostics -fansi-escape-codes -g sfml.cpp
-o sfml -I /opt/homebrew/Cellar/sfml/2.6.0/include -L
/opt/homebrew/Cellar/sfml/2.6.0/lib -lsfml-graphics -lsfml-window -lsfml-system
而不是分别编译文件“sfml.cpp”和“my_graphics.cpp”以及链接到每个文件的库。 我将它们编译在一起,并链接了库。
命令:
clang++ -std=gnu++14 -std=c++17 -fcolor-diagnostics -fansi-escape-codes -g sfml.cpp my_graphics.cpp -o program -I /opt/homebrew/Cellar/sfml/2.6.0/include -L /opt/homebrew/Cellar/sfml/2.6.0/lib -lsfml-graphics -lsfml-window -lsfml-system