I have the code: loading* loadingScreen = new loading(device);
When I compile the program, the compiler complains that loading screen wasn't declared:
error: 'loadingScreen' was not declared in this scope
loading* loadingScreen = new loading(device);
^
I'm unsure what's causing this. What I've tried:
Rewriting it so that the constructor isn't run.
Relocating the declaration to a different section of code.
Making sure my classes are included correctly.
Here's my main.cpp file:
#include <iostream>
#include <irrlicht.h>
#include <future> // std::async, std::future
#include <chrono> // Millisecond timer
#include <pthread.h>
#include <loading.h>
#include <fps.h>
bool loading = false;
struct load_struct {
irr::IrrlichtDevice *device;
fps *fpsLevel;
};
void load(void * loadingStruct)
{
loading = true;
struct load_struct *args = (struct load_struct *) loadingStruct;
loading = false;
pthread_exit(NULL);
}
int main()
{
//Create display to optimal settings.
irr::IrrlichtDevice *device = irr::createDevice(irr::video::EDT_NULL);
irr::s32 depth = device->getVideoModeList()->getDesktopDepth();
irr::core::dimension2d<irr::u32> resolution = device->getVideoModeList()->getDesktopResolution();
device->drop();
device = irr::createDevice(irr::video::EDT_OPENGL, resolution, depth, true, true, true, NULL); // TODO: Change last parameter
if(device==NULL)
{
std::cout << "Unable to create device! Do you have graphics drivers installed?" << std::endl;
return 1;
}
//Open data files
device->getFileSystem()->addFileArchive("Resources",true,true,irr::io::EFAT_ZIP);
device->getFileSystem()->addFileArchive("Video.tar");
device->getFileSystem()->addFileArchive("Textures.tar");
device->getFileSystem()->addFileArchive("Models.tar");
device->getFileSystem()->addFileArchive("Audio.tar");
//Load first room.
loading* loadingScreen = new loading(device);
fps *fpsLevel = new fps();
pthread_t creationThread;
struct load_struct loadingStruct;
loadingStruct.device = device;
loadingStruct.fpsLevel = fpsLevel;
//pthread_create(creationThread,NULL,load,(void *)&loadingStruct); Fix me!
while(loading==false)
{
loadingScreen->update();
std::this_thread::sleep_for(std::chrono::milliseconds(1000/60));
}
loadingScreen->kill();
// Run first room.
fpsLevel->run();
//Clean up.
device->drop();
return 0;
}
Here's my loading.h file:
#include <irrlicht.h>
#include <string>
#ifndef LOADING_H
#define LOADING_H
class loading
{
public:
loading(irr::IrrlichtDevice *device);
void update();
void kill();
protected:
int slide;
static const int SLIDES_AMOUNT = 60;
const std::string FILENAME_TEMPLATE = "Loading_Screen/%.png";
irr::video::ITexture* slides[SLIDES_AMOUNT];
};
#endif // LOADING_H
Any help would be appreciated!
The problem might be caused by the fact that you've got two different things called loading:
First, there's your class loading. But then, there's also the variable bool loading. So when you do:
loading* loadingScreen = new loading(device);
the compiler is confronted with an ambiguity and seems to prefer the variable loading over the type loading (I'm not an C++ pro and can't explain why this is the case; my guess is it's because the variable is the most "recent" definition of that name).
The fix is pretty easy: make the two names different. Since C++ is case-sensitive you should adopt the convention of starting class names with an uppercase letter: make that class Loading and Loading* loadingScreen = new Loading(device);.
Related
I am making a small game using SFML.
I want to load all my resources in one go when the game launches, so every time a new entity is created new resources don't need to be loaded to memory slowing down the game.
I have made a header file with a namespace for each kind of resource I need:
#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
#include "spritesheet.h"
namespace PlayerSprite {
extern Spritesheet playerSpritesheet;
extern sf::Sprite sp1, sp2, sp3, sp4, sp5, sp6;
extern int width = 16;
extern int height = 16;
}
namespace ButtonSprite {
extern Spritesheet buttonSpritesheet;
extern sf::Sprite button;
extern int width = 32;
extern int height = 16;
}
class Resources {
public:
Resources() = default;
void loadResources();
};
Now I don't know much about namespaces only very basic stuff, this is the first reason to use one.
Now in the cpp file:
#include <iostream>
#include "../headers/resources.h"
void Resources::loadResources() {
// PLAYER
PlayerSprite::playerSpritesheet.setSprite("./res/img/tiles.png");
PlayerSprite::sp1 = PlayerSprite::playerSpritesheet.getSprite(0, 0, PlayerSprite::width,
PlayerSprite::height);
PlayerSprite::sp2 = PlayerSprite::playerSpritesheet.getSprite(32, 0, PlayerSprite::width,
PlayerSprite::height);
PlayerSprite::sp3 = PlayerSprite::playerSpritesheet.getSprite(48, 0, PlayerSprite::width,
PlayerSprite::height);
PlayerSprite::sp4 = PlayerSprite::playerSpritesheet.getSprite(64, 0, PlayerSprite::width,
PlayerSprite::height);
PlayerSprite::sp5 = PlayerSprite::playerSpritesheet.getSprite(80, 0, PlayerSprite::width,
PlayerSprite::height);
PlayerSprite::sp6 = PlayerSprite::playerSpritesheet.getSprite(0, 16, PlayerSprite::width,
PlayerSprite::height);
// PLAYER
// BUTTONS
ButtonSprite::buttonSpritesheet.setSprite("./res/img/tiles.png");
ButtonSprite::button = ButtonSprite::buttonSpritesheet.getSprite(48, 16, 32, 16);
// BUTTONS
}
I then call this function in the main game file, but when I run I get this error in the player class:
undefined reference to 'PlayerSprite:sp1'
I don't know if this is because of the namespace declaration, or me coding the system wrong.
After looking at some comments on this question I have added this:
void Resources::allocateStorage() {
sf::Sprite PlayerSprite::spritesheet;
sf::Sprite PlayerSprite::sp1;
}
In the cpp file, but I am now getting this error:
unqualified-id in declaration before ';' token on the 1st line after the implementation of the function.
The problem seems to be that the variables are not actually defined anywhere, just declared. When using extern, the compiler will assume that this variable exists, so the compiler can continue on assuming that the variable exists. The linker will then come in, and see where that variable exists. If it does not, you get an undefined reference error. To fix this, you need to define the variables somewhere.
For example, in say resources.cpp, you would have:
#include "../headers/resources.h"
sf::Sprite PlayerSpriter::sp1;
sf::Sprite PlayerSpriter::sp2;
sf::Sprite PlayerSpriter::sp3;
// etc...
void Resources::loadResources() {
// …
}
This is in addition to what you already have in your header.
NOTE: From your edit, this would occur outside any function.
I am using gdal to do some raster works, well it has a GDALWarpAppOptionsSetProgress function which gets an static function to show its progcess. here you can find its link :Link
and this link
http://gdal.sourcearchive.com/documentation/1.6.0/gdal_8h_5703b651695c0cbe6f3644a0a18dda8b.html
well I know I must write an static function to use it, here is my function
static int My_FN_GDALTermProgress( double dfComplete, const char *pszMessage, void *pData)
{
if(progressBar){
progressBar->setValue(FN_GDAL_PROGRESS_VALUE);
}
double FN_GDAL_PROGRESS_VALUE = dfComplete * 100;
return TRUE;
}
well i have a class named gdal_dem which is like this
#include "gdal_dem.h"
#include "gdal_wrap.h"
#include <qdebug.h>
#include <iostream>
#include "cpl_string.h"
#include "gdal_priv.h"
#include "ogr_spatialref.h"
#include "gdal_utils_priv.h"
#include "cpl_error.h"
#include <QString>
#include "commonutils.h"
#include <QFile>
gdal_dem::gdal_dem(QString SrcFilename):
SrcFile(SrcFilename)
{
}
float FN_GDAL_PROGRESS_VALUE = 0.0f;
static int My_FN_GDALTermProgress(double dfComplete,
CPL_UNUSED const char * pszMessage,
CPL_UNUSED void * pProgressArg )
{
FN_GDAL_PROGRESS_VALUE = dfComplete * 100;
printf("Progress: %f\n",FN_GDAL_PROGRESS_VALUE);
return true;
}
////
int gdal_dem::colorrelief(QString Dstanationfile,QString colorfile){
.....
if(!(psOptionsForBinary->bQuiet))
{
prgFunc=My_FN_GDALTermProgress;
GDALDEMProcessingOptionsSetProgress(psOptions, prgFunc,NULL);
}
......
}
In above code I can set the above mentioned function in processing option and it works fine. but my problem is when I want to update a progress bar. I have a QProgressBar and it is in my main class. How can I pass it into the static function? I tried these ways:
1- I tried to get progressbar in my gdal_dem and also defined a static variable in gdal_dem and tried to set its value and update it in My_FN_GDALTermProgress, the problem is because progressbar is also static I can see it in wrap.cpp's contractor,
2-I tried to define a new My_FN_GDALTermProgress function in my main apps class but it must be static and I faced this error cannot declare member function to have static linkage
3- I also tried this method but it does not work
https://www.badprog.com/c-errors-warnings-cannot-declare-member-function-static-void-myclassmymethod-to-have-static-linkage
Well, How can I pass a parameter to my gdal_dem class and update its value in an static class in it?
Use the pData argument. You can pass anything you want to it when registering the static function. In this case, you can pass a pointer to your QProgressBar object:
QProgressBar* qProgBarObj = // ...
GDALDEMProcessingOptionsSetProgress(psOptions, prgFunc, qProgBarObj);
The static function will then receive it as the third argument:
static int My_FN_GDALTermProgress(double dfComplete, const char *pszMessage, void *pData)
{
auto progBar = reinterpret_cast<QProgressBar*>(pData);
progBar->setValue(/* ... */);
// ...
}
I'm new to C++ and am trying to learn OpenGL. However, when I try to compile my program, I cannot refer to a namespace that I have already created in my header file. The code is as follows:
engine.hpp:
#ifndef ENGINE_HPP
#define ENGINE_HPP
// ...
namespace render {
void Initialise();
namespace inits {
bool glfw_init = false,
glfw_window_init = false,
gl_init = false;
}
}
#endif
engine.cpp:
#include "engine.hpp"
// ...
namespace render {
void Initialise() {
if (glfwInit() == GLFW_FALSE)
inits::glfw_init = false;
}
}
O
I'm not sure why this isn't compiling. I'm using MinGW (GCC) on Windows 10 (64-bit).
My compiler message is:
error: 'inits' has not been declared
Edit: Thank you everybody for your suggestions. It appears that although this was a compiler fluke (after my first edit, since others could not reproduce the issue and a reinstall fixed the issue), it is a symptom of a larger organisational problem within my code. Since I have only invested ~15 minutes into the program, I would prefer to completely rewrite this after learning more about the language. For now, I have created a class and solved the issue discussed. I'm a beginner, and any book/resource recommendations would be welcome!
You're using nested namespaces, so should be:
render::inits::glfw_init = false;
Your code does not what you think it does.
// file engine.hpp
namespace render {
void Initialise();
namespace inits {
bool glfw_init = false, // these variables will be emitted with
glfw_window_init = false, // every source file that
gl_init = false; // #include "engine.hpp"
}
}
will lead to errors ("mulitply defined symbols") at linking/loading. To avoid that you may declare the variables extern or use functions for setting/getting the state (stored in a variable defined in engine.cpp).
This has been driving me nuts for a long time now. I have followed every tutorial I could find on the internet (here are couple examples[ [1], [2] of the maybe half dozen good ones found via Google search), and still no clear explanation. Although it seems it must be something fairly simple as that lack of a documented explanation implies that it's something most people would take for granted.
How do I load a custom module into Lua?
On the advice of questions like this one, I have written a module that builds a shared library with the expectation that I would be able to load it through a require call. However, when I do that I get undefined symbol errors, despite those exact symbols appearing in the list from the command nm -g mylib.so.
Those two tutorials I linked before aim to create executables that look wrappers of the *.lua file. That is, the built *.exe file should be called to run the Lua program with the custom module.
I understand that these types questions are asked here fairly frequently (as noted in this answer), but I am still at a loss. I tried some of the binding packages (Luabind and OOLua), but those didn't work out great (e.g. my earlier question--which I did ultimately figure out, sort of).
I have implemented a class in C++
I have wrapped the constructors, destructors, and functions with thunks
I have built it errorless-ly as a shared library
Yet no matter what I get undefined symbol: ... errors when I try to load it as mod = require('mylib.so'). How do I do this?
Working Example of a Library of Functions
For the record, just registering a basic function works fine. The below code, when built as libluatest.so, can be run in Lua using the commands:
> require('libluatest')
> greet()
hello world!
libluatest.cpp
extern "C"
{
#include <lualib.h>
#include <lauxlib.h>
#include <lua.h>
}
#include <iostream>
static int greet(lua_State *L)
{
std::cout << "hello world!" << std::endl;
return 0;
}
static const luaL_reg funcs[] =
{
{ "greet", greet},
{ NULL, NULL }
};
extern "C" int luaopen_libluatest(lua_State* L)
{
luaL_register(L, "libluatest", funcs);
return 0;
}
Failing Example of a Class
This is what I am stuck on currently. It doesn't seem to want to work.
myObj.h
#include <string>
class MyObj
{
private:
std::string name_;
public:
MyObj();
~MyObj();
void rename(std::string name);
};
myObj.cpp
extern "C"
{
#include <lualib.h>
#include <lauxlib.h>
#include <lua.h>
}
#include <iostream>
#include "myObj.h"
void MyObj::rename(std::string name)
{
name_ = name;
std::cout << "New name: " << name_ << std::endl;
}
extern "C"
{
// Lua "constructor"
static int lmyobj_new(lua_State* L)
{
MyObj ** udata = (MyObj **)lua_newuserdata(L, sizeof(MyObj));
*udata = new MyObj();
luaL_getmetatable(L, "MyObj");
lua_setmetatable(L, -1);
return 1;
}
// Function to check the type of an argument
MyObj * lcheck_myobj(lua_State* L, int n)
{
return *(MyObj**)luaL_checkudata(L, n, "MyObj");
}
// Lua "destructor": Free instance for garbage collection
static int lmyobj_delete(lua_State* L)
{
MyObj * obj = lcheck_myobj(L, 1);
delete obj;
return 0;
}
static int lrename(lua_State* L)
{
MyObj * obj = lcheck_myobj(L, 1);
std::string new_name = luaL_checkstring(L, 2);
obj->rename(new_name);
return 0;
}
int luaopen_libmyObj(lua_State* L)
{
luaL_Reg funcs[] =
{
{ "new", lmyobj_new }, // Constructor
{ "__gc", lmyobj_delete }, // Destructor
{ "rename", lrename }, // Setter function
{ NULL, NULL } // Terminating flag
};
luaL_register(L, "MyObj", funcs);
return 0;
}
}
Compiled into libmyObj.so using a simple CMake build with C++11 standard flags on.
Error
> require('libmyObj')
error loading module 'libmyObj' from file './libmyObj.so':
./libmyObj.so: undefined symbol: _ZN5MyObjC1Ev stack traceback: [C]:
? [C]: in function 'require' stdin:1: in main chunk [C]: ?
I am dealing with Lua 5.1 on Ubuntu 14.04.
I am wondering if it has something to do with the mix of C and C++...
It seems that you do not implement:
MyObj() ; ~MyObj();
and be careful with luaopen_* function, since module name is myObj, function name should be luaopen_libmyObj.
I've been getting weird compile errors all over the place in a simple hunter/prey simulation (mostly because the professor hasn't explained the syntax for inherited classes and virtual functions very well) and I'm completely stuck on one issue. In this program, "Creatures" (an abstract class with "Hunter" and "Prey" children) walk around a "Grid" class in a Move(), Breed(), Die() cycle.
I'm getting the following errors: "C2027: use of undefined type 'Creature'" and "C2227: left of '->face' must point to class/struct/union/generic type" at the line specified in below (all my code's in the header because several students were getting unresolved externals in another project and the professor told us to just put it all in the headers). Let me know if I need to post more code.
I've gotten several other errors that I couldn't explain before this that seemed to be solved through a seemingly random combination of adding/removing included headers and pre-declaring classes, but an actual explanation of what's going wrong would be much appreciated so I'm not just flailing in the dark until it works. I understand the concept of what we're trying to do and even how to go about it for the most part, but as I mentioned, we didn't spend any time on the syntax of how to properly set up multiple files so that everyone works smoothly so any detailed explanation of how this should be done would be greatly appreciated.
Grid.h
#ifndef GRID_H
#define GRID_H
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "Constants.h"
#include "creature.h"
using namespace std;
class Creature;
class Grid
{
public:
Creature* grid[MAX_X][MAX_Y];
Grid() //Initalizes the grid and spawns random creatures
{
for(int i = 0; i < MAX_X; i++)
for(int j = 0; j < MAX_Y; j++)
grid[i][j] = NULL;
}
void Move() //Tells each creature on the grid to move
{
//Call creature.Move() on each cell (if not NULL)
}
void Breed() //Tells each creature to breed (if it can)
{
//Call creature.Breed() on each cell (if not NULL)
}
void Kill() //Tells each creature to die (if it's old)
{
//Call creature.Die() on each cell (if not NULL)
}
char** Snapshot() //Creates a char array "snapshot" of the board
{
//Produces a 2D char array of the grid for display
}
Creature* Get(Coords here) //Returns a pointer to the object at the specified position
{
return grid[here.x][here.y];
}
char Occupant(Coords here) //Returns the character of the specified position
{
if(!Get(here))
return FACE_EMPTY;
Creature* temp = Get(here);
return temp->face; //*** ERRORS APPEAR HERE ***
}
void Clear(Coords here) //Deletes the object at the specified position
{
if(Get(here))
delete Get(here);
grid[here.x][here.y] = NULL;
}
};
#endif // GRID_H
creature.h
#ifndef CREATURE_H
#define CREATURE_H
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "Constants.h"
#include "coords.h"
#include "grid.h"
using namespace std;
class Grid;
class Creature
{
public:
Grid* theGrid;
Coords position;
int stepBreed;
int stepHunger;
char face;
Creature(Grid* _grid, Coords _position, char _face) //Constructor
{
theGrid = _grid;
position = _position;
face = _face;
stepBreed = stepHunger = 0;
}
virtual Coords Move() = 0; //Allows the child to define it's own movement
virtual Coords Breed() = 0; //Allows the child to define it's own breeding
virtual bool Starve() = 0; //Allows the child to starve of its own accord
};
#endif // CREATURE_H
Your use of class Creature at the top of the file seems to indicate that you don't have access to the complete definition of Creature in this file. That makes it impossible for the compiler to do the -> operation on it - it doesn't know what the members of that class are! You need to have a complete definition of Creature in the same translation unit as this code. That is, Creature needs to be a complete type if you want to use it in this way.
Edit: Thanks for posting creature.h. Your problem (as mentioned in the comments below) is that you have a circular dependency problem. creature.h includes grid.h and vice versa. You'll need to break one of those links to get things working properly. In this case, removing #include "grid.h" from creature.h should do the trick - no code in creature.h depends on Grid being a complete type.