Problem Description:
I am working on making a Cart class that has a sf::Sprite
(cartSprite
) in each instance. However, the static sf::Texture
(cartTexture
) from which carts are generated is shared between all Cart objects. On construction of a Cart, the sprite is loaded from the texture.
According to the documentation, the sf::Texture
has a default constructor that:
Creates an empty texture.
However, when I compile the code below, that declares, but does not define, the sf::Texture
, I get linker errors:
/tmp/cclJ5hJp.o: In function `Cart::Cart(sf::Vector2<float> const&, sf::Color, float)':
main.cpp:(.text._ZN4CartC2ERKN2sf7Vector2IfEENS0_5ColorEf[_ZN4CartC5ERKN2sf7Vector2IfEENS0_5ColorEf]+0x46): undefined reference to `Cart::cartTexture'
main.cpp:(.text._ZN4CartC2ERKN2sf7Vector2IfEENS0_5ColorEf[_ZN4CartC5ERKN2sf7Vector2IfEENS0_5ColorEf]+0x87): undefined reference to `Cart::cartTexture'
main.cpp:(.text._ZN4CartC2ERKN2sf7Vector2IfEENS0_5ColorEf[_ZN4CartC5ERKN2sf7Vector2IfEENS0_5ColorEf]+0x9b): undefined reference to `Cart::cartTexture'
main.cpp:(.text._ZN4CartC2ERKN2sf7Vector2IfEENS0_5ColorEf[_ZN4CartC5ERKN2sf7Vector2IfEENS0_5ColorEf]+0xb6): undefined reference to `Cart::cartTexture'
collect2: error: ld returned 1 exit status
Does this mean that I should initialize (define) cartTexture
? If so, how do I do that at compile-time when the only constructors for sf::Texture
are "copy from another sf::Texture
" and the one mentioned above? I can't use a function call to load an image into it, right?
Compile the code with: g++ main.cpp -Wall -Wextra -Werror -std=c++11 -lsfml-graphics -lsfml-window -lsfml-system -o exec
Code:
main.cpp:
#include <SFML/Graphics.hpp>
#include <string>
#include <iostream>
#include <mutex>
class Cart : public sf::Drawable {
public:
// Constructor- create with position, orientation, and color.
Cart(const sf::Vector2f& cartPos_, sf::Color cartColor_, float cartAngle_) {
if (!cartTexture.loadFromFile(textureLoc)) {
std::cout << "File is nonexistent." << std::endl;
} else {
cartTexture.setSmooth(true);
cartTexture.setRepeated(false);
}
cartSprite.setTexture(cartTexture);
cartSprite.setPosition(cartPos_);
cartSprite.setRotation(cartAngle_);
cartSprite.setColor(cartColor_);
}
private:
void draw(sf::RenderTarget& target, sf::RenderStates states) const {
target.draw(cartSprite, states);
return;
}
static sf::Texture cartTexture;
static const std::string textureLoc;
sf::Sprite cartSprite;
};
const std::string Cart::textureLoc = "cart-empty.png";
int main() {
Cart testCart(sf::Vector2f(), sf::Color(200,200,200), 0);
return 0;
}