-1

I was testing around with SFML and structs, so I decided to write this small bit of code in C++ and it comes up with the failure of this:

/tmp/ccudZjgy.o: In function `fontconfig()':
main.cpp:(.text+0x96): undefined reference to `Text::font'
/tmp/ccudZjgy.o: In function `textconfig()':
main.cpp:(.text+0x146): undefined reference to `Text::font'
main.cpp:(.text+0x1fa): undefined reference to `Text::text'
/tmp/ccudZjgy.o: In function `window()':
main.cpp:(.text+0x3d8): undefined reference to `Text::text'
collect2: error: ld returned 1 exit status

This is my code:

#include <SFML/Graphics.hpp>

struct Text{
     static sf::Font font;
     static sf::Text text;  
};
void fontconfig()
{
     sf::Font font;
     font.loadFromFile("flower.ttf");
     Text Text1;
     Text1.font = font;
}

void textconfig()
{
     Text Text1;
     sf::Text text;
     text.setFont(Text1.font);
     text.setCharacterSize(100);
     text.setColor(sf::Color::Red);
     text.setString("Ugh...");
     text.setStyle(sf::Text::Bold);

     Text1.text = text;
}

 void window()
 {
        Text Text1;
        sf::RenderWindow window(sf::VideoMode(300, 150), "Hello");
        while (window.isOpen())
        {
              sf::Event event;
              while (window.pollEvent(event))
              {
                     if (event.type == sf::Event::Closed)
                     window.close();
              } 

              window.clear(sf::Color::White);
              window.draw(Text1.text);
              window.display();

              } 


}
int main()
{
 fontconfig();
 textconfig();
 window();
 return 0;
}
Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
James Bond
  • 120
  • 1
  • 9
  • Did you really mean to declare your `Text` member variables `static`? If you do you need to provide an external **definition**. See examples here: http://en.cppreference.com/w/cpp/language/static and https://stackoverflow.com/questions/185844/initializing-private-static-members – Galik Aug 07 '16 at 00:31
  • Why did you guys downvote? – James Bond Aug 09 '16 at 17:52

1 Answers1

1

The variables inside your functions are local variables. Because of the way namespacing works, local variables with the same name as global ones are referred to first, with the double colon before to refer to the global one if you want it like so:

Foo // refers to the default, local scope

::Foo // refers to the global scope

In other words, you never actually touch the global variables.

Instead, the local variables that you do modify are thrown away as you leave the function scope.

Rather, you should be passing your external resource classes as parameter references to the function if you wish to use a subroutine, mutator style, like so:

void textconfig(sf::Text& text); // pass by reference for a subroutine-focused, mutator style

CinchBlue
  • 6,046
  • 1
  • 27
  • 58