c++ - How to call on a function found on another file? -
i'm starting pick c++ , sfml library, , wondering if defined sprite on file appropriately called "player.cpp" how call on main loop located @ "main.cpp"?
here code (be aware sfml 2.0, not 1.6!).
main.cpp
#include "stdafx.h" #include <sfml/graphics.hpp> #include "player.cpp" int main() { sf::renderwindow window(sf::videomode(800, 600), "skylords - alpha v1"); while (window.isopen()) { sf::event event; while (window.pollevent(event)) { if (event.type == sf::event::closed) window.close(); } window.clear(); window.draw(); window.display(); } return 0; }
player.cpp
#include "stdafx.h" #include <sfml/graphics.hpp> int playersprite(){ sf::texture texture; if(!texture.loadfromfile("player.png")){ return 1; } sf::sprite sprite; sprite.settexture(texture); return 0; }
how need in "main.cpp" says window.draw(); in draw code. in parenthesis, there should name of sprite want load onto screen. far i've searched, , tried guessing. have not succeeded making draw function work sprite on other file. feel i'm missing big, , obvious (on either files), again, every pro once newb.
you can use header files.
good practice.
you can create file called player.h
declare functions need other cpp files in header file , include when needed.
player.h
#ifndef player_h // make sure don't declare function more once including header multiple times. #define player_h #include "stdafx.h" #include <sfml/graphics.hpp> int playersprite(); #endif
player.cpp
#include "player.h" // player.h must in current directory. or use relative or absolute path it. e.g #include "include/player.h" int playersprite(){ sf::texture texture; if(!texture.loadfromfile("player.png")){ return 1; } sf::sprite sprite; sprite.settexture(texture); return 0; }
main.cpp
#include "stdafx.h" #include <sfml/graphics.hpp> #include "player.h" //here. again player.h must in current directory. or use relative or absolute path it. int main() { // ... int p = playersprite(); //...
not such practice works small projects. declare function in main.cpp
#include "stdafx.h" #include <sfml/graphics.hpp> // #include "player.cpp" int playersprite(); // here int main() { // ... int p = playersprite(); //...
Comments
Post a Comment