Problems loading resources from function C++/SFML - c++

I have a stucture that I use to declare Textures, Sprites, Music, Fonts, Sounds, etc in a header. I then use a corresponding .cpp file to set said textures to their corresponding sprites, and so on.
I have created the struct object in main, and called the function. But When I build my program, I get a million "undeclared identifier" errors. What am I doing wrong? Here's my code:
resources.h:
#ifndef __SFML__resources__
#define __SFML__resources__
#include "SFML/Audio.hpp"
#include "SFML/Graphics.hpp"
struct resources
{
float opacity = 1.0;
sf::Texture texturePlayer;
sf::Texture textureSettingsMenu;
sf::Sprite spriteSaveMenu;
sf::Sprite spriteSettingsMenu;
//start screen texture
sf::Texture textureStart;
//gamestate background sprite
sf::Sprite spriteScreen;
sf::Font font;
sf::Font font2;
int loadResources();
// hundreds more lines of declarations below
//...
};
#endif
resources.cpp:
#include "resources.h"
int resources::loadResources()
{
if (!textureSaveMenu.loadFromFile("images/magicmenu3.png"))
return EXIT_FAILURE;
if (!textureSettingsMenu.loadFromFile("images/inventorymenu.png"))
return EXIT_FAILURE;
spriteSaveMenu.setTexture(textureSaveMenu);
spriteSettingsMenu.setTexture(textureSettingsMenu);
if (!textureStart.loadFromFile("images/skyocean.png"))
return EXIT_FAILURE;
if (!font.loadFromFile("fonts/arial.ttf"))
return EXIT_FAILURE;
if (!font2.loadFromFile("fonts/dominican.ttf"))
return EXIT_FAILURE;
if (!musicBattle.openFromFile("audio/musicBattle.ogg"))
return EXIT_FAILURE;
musicBattle.setVolume(20);
musicBattle.setLoop(true);
if (!musicOpening.openFromFile("audio/maintheme.ogg"))
return EXIT_FAILURE;
musicOpening.setVolume(30);
musicOpening.setLoop(true);
if (!musicDefeat.openFromFile("audio/defeat.ogg"))
return EXIT_FAILURE;
musicDefeat.setVolume(50);
musicDefeat.setLoop(true);
if (!musicForest.openFromFile("audio/forest.ogg"))
return EXIT_FAILURE;
musicForest.setVolume(10);
musicForest.setLoop(true);
if (!musicWorldMap.openFromFile("audio/bluefields.ogg"))
return EXIT_FAILURE;
musicWorldMap.setVolume(40);
musicWorldMap.setLoop(true);
if (!musicVillage.openFromFile("audio/welcomehome.ogg"))
return EXIT_FAILURE;
musicVillage.setVolume(40);
musicVillage.setLoop(true);
//every single declared resource is set within this function
//but the function is too large to display fully here
}
main.cpp:
#include "SFML/Audio.hpp"
#include "SFML/Graphics.hpp"
#include <iostream>
#include "random.h"
#include "player.h"
#include "entity.h"
#include "projectile.h"
#include "enemy.h"
#include "textDisplay.h"
#include "pickup.h"
#include "wall.h"
#include "sword.h"
#include "npc.h"
#include "battlemenu.h"
#include "cursor.h"
#include "name.h"
#include "itemshop.h"
#include "characterselection.h"
#include "mainmenu.h"
#include "exp.h"
#include "drops.h"
#include "weaponshop.h"
#include "armorshop.h"
#include "startmenu.h"
#include "room.h"
#include "resources.h"
int main()
{
//create the main window
sf::RenderWindow window(sf::VideoMode(720, 500), "Sky Ocean");
window.setFramerateLimit(60);
window.setKeyRepeatEnabled(false);
//View
sf::View view1(sf::FloatRect(200, 200, 300, 200));
view1.setSize(sf::Vector2f(window.getSize().x, window.getSize().y));
view1.setCenter(sf::Vector2f(view1.getSize().x / 2, view1.getSize().y / 2));
window.setView(view1);
//load resources
struct resources resources1;
resources1.loadResources();
//class object
class player Player1;
Player1.sprite.setTexture(texturePlayer);
class player Player2;
Player2.sprite.setTexture(texturePlayer);
Player2.rect.setScale(1.6, 1.6);
Player2.sprite.setScale(1.6, 1.6);
//...
}

Firstly, I recommend you to read something about header files.
resources.h indeed doesn't contain declaration of identifiers used.
You will have to #include header file which contains those declarations so compiler will be able to see them. Please read SFML declaration to see which modules need to be included and #include them into header file, now you're including them only into main.cpp so only main.cpp contains declaration of identifiers. When compiler reads resources.cpp it doesn't see those declaration, henceundeclared identifier error.
resources.h for example should look like this:
//...
#include "entity.h"
#include <SFML/Graphics.hpp>
#include <Whatever.hpp>
struct resources
{
//...

Related

std::any bad cast whenever a function inside a header is implemented in a cpp file returns it

This is my main.cpp
#include <iostream>
#include <unordered_map>
#include <string>
#include "myclass.h"
int main(int argc, const char * argv[]) {
any a = myclass::returnthis();
unordered_map<string, any>* hmap = any_cast<unordered_map<string, any>*>(a);
return 0;
}
this is myclass.h
#ifndef myclass_h
#define myclass_h
#include <any>
using namespace std;
class myclass {
public:
static any returnthis();
};
#endif /* myclass_h */
and this is myclass.cpp
#include "myclass.h"
#include <any>
#include <unordered_map>
#include <string>
any myclass::returnthis() {
return new unordered_map<string, any>();
}
Now, any_cast will report bad any cast. I am working on macOS and I have tried Xcode and CLion.
However, if I put the implementation of the function inside the header file, the problem vanishes. Why?

Error LNK2005 and LNK1169 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
There are many questions on this, but none solve my problem. I am trying to use multiple files. I have no idea where the problem is, so I will include all the top lines (#include, #pragma, etc.)
This problem arose when I was creating the class for Cubes.cpp (and in Cubes.h).
main.cpp
#include <iostream>
#include "Cubes.h"
#include "Common functions.h"
#include "Global.h"
#include <SFML/Graphics.hpp>
Cubes.cpp
#include <iostream>
#include "Cubes.h"
#include "Common functions.h"
#include "Global.h"
#include <SFML\Graphics.hpp>
#include <vector>
#include <string>
// Later on in code, where I think it went wrong:
Render::Render()
{
this->rot;
this->boxCoords;
this->rlBoxCol;
this->gridSize;
this->cubeSize;
this->offset;
}
void Render::setRotation(std::vector<float> setRot)
{ // Set rotation
rot = setRot;
}
std::vector<float> Render::getRotation()
{ // Get rotation
return rot;
}
void Render::setCoordinates(std::vector<int> setBoxCoords)
{
boxCoords = setBoxCoords;
}
std::vector<int> Render::getCoordinates()
{
return boxCoords;
}
void Render::setColours(std::vector<std::string> setRlBoxCol)
{
rlBoxCol = setRlBoxCol;
}
std::vector<std::string> Render::getColours()
{
return rlBoxCol;
}
void Render::setSizeOfGrid(int setGridSize)
{
gridSize = setGridSize;
}
int Render::getSizeOfGrid()
{
return gridSize;
}
void Render::setSizeOfCubes(int setCubeSize)
{
cubeSize = setCubeSize;
}
int Render::getSizeOfCubes()
{
return cubeSize;
}
void Render::setOffset(std::vector<int> setOffset)
{
offset = setOffset;
}
std::vector<int> Render::getOffset()
{
return offset;
}
void Render::display()
{
// Long code, not going to show it
}
Cubes.h
#pragma once
#include <vector>
#include <string>
// Also later on in Cubes.h ...
class Render
{
private:
std::vector<float> rot;
std::vector<int> boxCoords;
std::vector<std::string> rlBoxCol;
int gridSize;
int cubeSize;
std::vector<int> offset;
public:
Render();
void setRotation(std::vector<float> setRot);
std::vector<float> getRotation();
void setCoordinates(std::vector<int> setBoxCoords);
std::vector<int> getCoordinates();
void setColours(std::vector<std::string> setRlBoxCol);
std::vector<std::string> getColours();
void setSizeOfGrid(int setGridSize);
int getSizeOfGrid();
void setSizeOfCubes(int setCubeSize);
int getSizeOfCubes();
void setOffset(std::vector<int> setOffset);
std::vector<int> getOffset();
void display();
};
Common functions.cpp
#include <iostream>
#include "Common functions.h"
#include <vector>
#include <string>
Common functions.h
#pragma once
#include <vector>
Global.h
#pragma once
#include <SFML\Graphics.hpp>
extern sf::RenderWindow Window(sf::VideoMode(500, 500), "Maximize window to play the game");
extern std::string status = "NULL";
With the errors:
LNK2005
"class sf::RenderWindow Window" (?Window##3VRenderWindow#sf##A) already defined in Cubes.obj
C:\Users\George\Documents\C++\Projects\Don't fall\Don't fall\main.obj 1
.
LNK2005
"class std::basic_string,class std::allocator > status" (?status##3V?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##A) already defined in Cubes.obj
C:\Users\George\Documents\C++\Projects\Don't fall\Don't fall\main.obj 1
.
LNK1169
one or more multiply defined symbols found
C:\Users\George\Documents\C++\Projects\Don't fall\Debug\Don't fall.exe 1
.
I have been stuck on this problem for a while, so any help would be greatly appreciated!
EDIT
I answered my own question, as no one found a solution.
Solution (solved my own problem)
In Global.h, I changed the code to:
#pragma once
#include <SFML\Graphics.hpp>
extern sf::RenderWindow Window;
extern std::string status;
and in Cubes.cpp, I changed it to:
#include <iostream>
#include "Cubes.h"
#include "Common functions.h"
#include "Global.h"
#include <SFML\Graphics.hpp>
#include <vector>
#include <string>
sf::RenderWindow Window(sf::VideoMode(500, 500), "Maximize window to play the game");
std::string status = "NULL";

error LNK2001: unresolved external symbol "public: static class sf::RenderStates const sf::RenderStates::Default"

Here's the code:
Engine.h
#include <SFML/Audio.hpp>
#include <SFML/Config.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
class Engine
{
public:
Engine(sf::RenderWindow & wd);
void run(sf::RenderWindow & wd);
sf::Sprite player;
sf::Texture playerTexture;
};
Engine.cpp
#include "Engine.h"
Engine::Engine(sf::RenderWindow & wd) : player(), playerTexture()
{
}
void Engine::run(sf::RenderWindow & wd)
{
if (!playerTexture.loadFromFile("image/char.png")) {}
player.setTexture(playerTexture);
while (wd.isOpen())
{
sf::Event event;
while (wd.pollEvent(event))
{
if (event.type == sf::Event::Closed)
wd.close();
}
wd.clear();
wd.draw(player);
wd.display();
}
}
main.cpp
#include <SFML/Audio.hpp>
#include <SFML/Config.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include "Engine.h"
int main()
{
sf::RenderWindow * wd = new sf::RenderWindow(sf::VideoMode(800, 600), "Lumia");
Engine * eg = new Engine(*wd);
eg->run(*wd);
return EXIT_SUCCESS;
}
if I delete wd.draw(player); from Engine.cpp, this error doesn't occur, it seems like I can't draw anything, am I defining a default constructor and not calling it? Or am I passing arguments in aa wrong way? Please explain me why this error occurs and give me a reasonably solution, thanks for further answers.
OBS: SFML 2.1, Microsoft Visual Studio 2013, i7, 8gb ram, geforce gtx850M 4gb video ram, Windows 8.1.
You should add your file names of *.lib files to vs' linker.
Steps: Open your project Property pages.(Press Alt+F7 in vs). Expand "Configuration Properties". Expand "Linker". You will find item "Input" under "Linker" and click the "Input". On the right side,you will find a item "Additional Dependencies". Add your lib file names here.(for example lib1.lib;lib2.lib...,separate the libraries with semicolon).

boost compile error Mac OS X 10.7.4

I want to use boost on my Mac.
Mac OS X 10.7.4
Xcode 4.5
I installed boost by homebrew.
brew install boost
Boost version is 1.49.0.
And I set up my Xcode project.
Add Header search path.
/usr/local/Cellar/boost/1.49.0/include
Add libraries
libboost * .dylib
When I compile my project, I have many errors. Clang LLVM 1.0 Error.
( I want to upload an image, but I can't upload becase I don't have more than 10 reputation. )
use of undeclared identifier 'nullptr_t'; did you mean 'nullptr'?
use of undeclared identifier 'nullptr_t'; did you mean 'nullptr'?
too few template arguments for class template '__is_function'
use of undeclared identifier 'nullptr_t'; did you mean 'nullptr'?
field has incomplete type 'std::exception_ptr'
expected ';' at end of declaration list
no member named 'memcpy' in namespace 'std::__1'; did you mean 'memcpy'?
no member named 'memcpy' in namespace 'std::__1'; did you mean 'memcpy'?
expected ';' at end of declaration list
expected ';' at end of declaration list
C++ requires a type specifier for all declarations
'operator==' cannot be the name of a variable or data member
use of undeclared identifier 'nullptr_t'; did you mean 'nullptr'?
expected ';' at end of declaration
expected unqualified-id
expected ';' at end of declaration list
unknown type name 'nullptr_t'
unknown type name 'nullptr_t'
qualified reference to 'shared_ptr' is a constructor name rather than a type wherever a constructor can be declared
too many errors emitted, stopping now
I checked this question.
XCode with boost "Semantic Issue - undeclared identifier va_start"
But I couldn't find answers.
Please let me know if there is a solution.
The header file using boost is like this.
GLTexture.hpp
#pragma once
#ifndef __GL_TEXTURE_HPP__
#define __GL_TEXTURE_HPP__
// Standard libraries.
#include <iostream>
#include <fstream>
#include <string>
#ifdef _WIN32
#pragma warning (push)
#pragma warning (disable:4819)
#endif
// Smart pointers.
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_array.hpp>
// Foreach macros.
#include <boost/foreach.hpp>
// Regular expression.
#include <boost/regex.hpp>
// Image I/O.
#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/gil_all.hpp>
#include <boost/gil/extension/io/jpeg_io.hpp>
#include <boost/gil/extension/io/png_io.hpp>
// File operations,
#include <boost/filesystem.hpp>
// Linear algebra,
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
// String functions.
#include <boost/algorithm/string.hpp>
// Serialization
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/version.hpp>
#ifdef _WIN32
#pragma warning (pop)
#endif
// OpenGL and OpenGL Utility Toolkit
#ifdef _WIN32
#include <GL/glew.h>
#include <GL/GLUT.h>
#elif defined __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#endif
#include "TextureManager.hpp"
#include <time.h>
class TextureManager;
using namespace std;
/// function to convert RGB image to RGBA image.
/// Filling its alpha channel with 255.
/// This function is called from boost::gil::copy_and_convert_pixels()
namespace boost {
namespace gil {
template <> void color_convert<rgb8_pixel_t,rgba8_pixel_t>(const rgb8_pixel_t& src,rgba8_pixel_t& dst);
}
}
class GLTexture
{
public:
//Destructor
~GLTexture();
//Return instance of GLTexture
static boost::shared_ptr<GLTexture> getInstance(const std::string& filename, bool _isVolatile = true);
//Load image file and generate texture
bool LoadFromFile(boost::shared_ptr<GLTexture> texture);
//Bind texture when the texture exists. If the texture doesn't exist, this method generates a texture.
static void bindTexture(boost::shared_ptr<GLTexture> texture);
//Setter of texFileName
void setTextureFile(const std::string filename);
//Setter of volatile Flag
void setIsVolatile(bool _isVolatile);
//Getter of texture ID
inline const GLuint& getTextureID(void)const{
return this->texture;
};
//Overload of operator to sort list
friend bool operator <(const boost::shared_ptr<GLTexture>& texture1, const boost::shared_ptr<GLTexture>& texture2);
friend std::ostream& operator <<(ostream& os, const boost::shared_ptr<GLTexture>& texture);
public:
GLuint texture; //texture id
std::string texFileName; //image file path
int width; //width of image
int height; //height of image
clock_t start, end; //start is the timing of bindTexture, end is the timing of delete, these are used to sort list.
bool isVolatile; //the flag whether this texture is volatile or not. true is volatile, and false is not volatile. To keep texture, this is false.
bool isRead; //the flag whether this texture already exists in texturelist. true means "exists", false means "not exists".
boost::shared_ptr<boost::gil::rgba8_image_t> pixelData_ptr; //smart pointer to contain pixelData
boost::shared_ptr<boost::gil::rgba8_image_t::const_view_t> viewwithAlpha_ptr; //smart pointer to contain viewData
private:
//Forbid copy constructor
GLTexture();
GLTexture(const std::string& imageFilePath, bool _isVolatile = false);
GLTexture(const GLTexture& glTexture);
GLTexture& operator = (const GLTexture& glTexture);
//load image from SSD
bool LoadImage(const std::string& filename);
};
#endif
TextureManager.hpp
#pragma once
#ifndef __TEXTURE_MANAGER_HPP__
#define __TEXTURE_MANAGER_HPP__
// Standard libraries.
#include <iostream>
#include <fstream>
#include <string>
#ifdef _WIN32
#pragma warning (push)
#pragma warning (disable:4819)
#endif
// Smart pointers.
#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
// Foreach macros.
#include <boost/foreach.hpp>
// Regular expression.
#include <boost/regex.hpp>
// Image I/O.
#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/gil_all.hpp>
#include <boost/gil/extension/io/jpeg_io.hpp>
#include <boost/gil/extension/io/png_io.hpp>
// File operations,
#include <boost/filesystem.hpp>
// Linear algebra,
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
// String functions.
#include <boost/algorithm/string.hpp>
// Serialization
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/version.hpp>
#ifdef _WIN32
#pragma warning (pop)
#endif
// OpenGL and OpenGL Utility Toolkit
#ifdef _WIN32
#include <GL/glew.h>
#include <GL/GLUT.h>
#elif defined __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#endif
#include "GLTexture.hpp"
class GLTexture;
class TextureManager
{
public:
TextureManager(void);
~TextureManager(void);
//Generate Texture
static void genTexture(boost::shared_ptr<GLTexture> texture);
static void setTexture(const boost::shared_ptr<GLTexture> texture);
static void deleteTexture();
static bool checkList(const std::string& filename);
private:
//Forbid copy constructor
TextureManager(const TextureManager& texManager);
TextureManager& operator = (const TextureManager& texManager);
};
#endif
Did you use recursive search path for the headers? If so change it to non-recursive. That might solve the problem.
I had similary problem!I soved the problem that:
Xcode->Buid Setting->C++ language Dialect(GNU++11)
->C++Standard Library(libc++(LLVM C++ with C++ 11)
I needed to add
#include <cstring>
http://en.cppreference.com/w/cpp/string/byte/memcpy

Qt namespace duplicate id error

I hope is not a question too specific... But I will be really thankfull if you could help!
when I build my application I get this error, do you know why?:
ld: duplicate symbol colors::white in mainwindow.o and main.o
collect2: ld returned 1 exit status
Here is the definition of the main:
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
and here is the definition of main window:
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
glwidget = new MyGLBox(ui->centralWidget);
startTimer(11);
//test frame
BasicShapes shapes;
Polygon3 square = shapes.create_square(V3(0.,0.,0.),V3(1.0,1.0,1.),colors::cyan);
Polygon3 cube = shapes.create_cube(V3(-1.,-1.,-1.),V3(1.,1.,1.),colors::purple);
Polygon3 triangle = shapes.create_triangle(V3(0,1.,0),V3(1.,1.,1.),5.,colors::green);
//other stuff...
ui->vLayoutGLview->addWidget(glwidget); //add the glwidget to the ui framework
}
colors is a namespace defined in the file colors.h:
namespace colors{
Color white(1.,1.,1.,0.);
Color black(0.,0.,0.,0.);
Color red(1.,0.,0.,0.);
Color green(0.,1.,0.,0.);
Color blue(0.,0.,1.,0.);
Color yellow(1.,1.,0.,0.);
Color purple(1.,0.,1.,0.);
Color cyan(0.,1.,1.,0.);
}
here is my file list:
colors.h
#include <string>
#include <iostream>
#include <sstream>
mainwindow.h
#include <QMainWindow>
#include "myglbox.h"
#include "sceneobject.h"
mathvector.h
#include <vector>
#include <cmath>
#include <string>
#include <iostream>
#include <sstream>
#include "colors.h"
myglbox.h
#include <QGLWidget>
#include <QtOpenGL>
#include <vector>
#include "mathvector.h"
sceneobject.h
#include "mathvector.h"
I'm pretty sure I didn't included two time the same file(but maybe I missed it), and anyway the header are protected by the header guards.
do you have any idea why I get a duplicate id error? without the namespace it compiled fine, but a namespace with the standard color will be really useful...
Objects defined in a header file will be duplicated in every compilation unit that includes that header, leading to duplicate definition errors. These should either be extern (and defined elsewhere), or (my preference) made into free functions:
Colors.h
namespace color
{
const Color& white();
const Color& black();
// etc...
}
Colors.cpp
#include "colors.h"
namespace color
{
const Color& white()
{
static Color w(1.,1.,1.,0.);
return w;
}
const Color& black()
{
static Color b(0., 0., 0., 0.);
return b;
}
}
Then you can use them easily as:
Color white_copy = colors::white();
const Color& black = colors::black();