C++ - Initialze static variable with global scope - c++

I have included a static c++ string array in the header file. I get a segfault
when I try to access it in the source file.
Here are the details.
OS : Linux
Compiler : g++
job.hpp
static string values[2] = {"hello","welcome"};
class Job
{
public:
void getValues();
};
job.cpp
#include "job.hpp"
void Job::getValues()
{
// Seg Fault Here
// i value is either 0 or 1 and is based on some external flag
cout << values[i] << endl;
}
I believe the values array is not getting initialized. This code works with xlc++ compiler on AIX. Is there any g++ compiler flag to initialize the static variables.

Why not make your 'values' array into a static attribute of the class? Something like the following might work.
job.h
#ifndef JOB_H
#define JOB_H
#include <string>
#include <iostream>
using namespace std;
class Job
{
public:
Job();
void getValues() const;
//declare static variable in .hpp file
static string values[2];
private:
};
#endif
job.cpp
#include "job.h"
//initialize variable in .cpp file
string Job::values[2]={"hello", "welcome"};
Job::Job(){}
void Job::getValues() const
{
cout << values[i] << endl;
}

Related

C++ compiling error

I have a compiling error in C++ using classes. I have worked with classes before and have never encountered this error. I have tried adding static before the method ImprtData but that only prompted more errors.
error: invalid use of non-static member function bank.ImprtData;
here is my .cpp
#include "componets.h"
User::User() {
std::cout << "loaded" << std::endl;
}
void User::ImprtData() {
std::cout << "loaded.\n";
}
and here is my .h
#include <sstream>
#include <fstream>
#include <vector>
#include <iostream>
#include <string>
class User {
public:
User();
void write();
void launch_main_menu();
void login();
void ImprtData();
private:
void deposit();
void withdrawl();
std::string account_name;
int account_pin;
float account_balance;
std::string account_user_name;
};
and finally my main
#include "componets.h"
int main() {
std::cout << "Welcome to Bank 111.\n";
User bank;
bank.ImprtData;
return 0;
}
This is essentially a simple typo. Replace
bank.ImprtData;
with
bank.ImprtData();
to call the function. The expression bank.ImprtData is confusing the compiler since it's interpreting it as the address of a function, and issues a diagnostic since the function is not static.
bank.ImprtData; should be bank.ImprtData();

Define a static integer in a header with default value

How can I define an integer in a header file so that each cpp file which includes the header will have static const int id=0 while giving the ability to cpps to redefine it with other value.
I tried to used weak symbol but couldn't make it work.
If you are ok with preprocessor definitions you could do this:
// header.h
#ifndef CLASSID
#define CLASSID 0
#endif
static int id=CLASSID;
// class.cpp
#define CLASSID 1
#include "header.h"
This way a source file may override the default, but may also omit it, which is the sort of weak approach you mentioned.
Here's another solution that uses static variables:
// log.h
#ifndef LOG_H
#define LOG_H
#include <iostream>
#define SETLOGID(v) static logidsetter _logidsetter(_logid, v);
#define LOG(v) std::cout << "id: " << _logid << ": " << (v) << std::endl;
class logidsetter
{
public:
logidsetter(int &id, int val)
{
id = val;
}
};
static int _logid = 0;
#endif
// myclass.h
class myclass
{
public:
myclass();
void run(void);
};
// myclass.cpp
#include "log.h"
#include "myclass.h"
SETLOGID(42)
myclass::myclass()
{
LOG("myclass::cons");
}
void myclass::run(void)
{
LOG("myclass::run");
}
// main.cpp
#include "myclass.h"
#include "log.h"
SETLOGID(1)
int main()
{
myclass mc;
LOG("here's main");
mc.run();
}
The log header defines the static int _logid and provides the macro SETLOGID and the class idsetter. The cpp file may use SETLOGID to redefine the static value. This is done with an instantiation of the class idsetter along with the address of _logid and the desired value. The trick allows to bypass C++'s One Definition Rule.
The output looks like:
id: 42: myclass::cons
id: 1: here's main
id: 42: myclass::run

How do I get values from a struct in a different cpp file?

I think there are many solutions outside for my problem but I dont get it, I'm kind of new to structs - so please help me..
OK my problem is I declare a struct in my header.h file and there is a function also inside that puts a string in one of the struct values and in the header file I can also output the string, but I want that struct and that !!value!! in a different cpp file where I can access to that value - so here is my code
header.h
#include <iostream>
#include <string.h>
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
struct FUNCTIONS
{
std::string f_name;
};
//extern FUNCTIONS globalStruct;
//put in struct variable
void put2struct()
{
struct FUNCTIONS struct1;
struct1.f_name = "FUNCTION";
std::cout << "Functionname: " << struct1.f_name << std::endl;
}
#endif //FUNCTIONS_H
and main.cpp
#include <iostream>
#include <string.h>
#include "header.h"
using namespace std;
int main(int argc, char const *argv[])
{
struct FUNCTIONS globalStruct;
put2struct();
//FUNCTIONS struct1;
std::cout << "Functionname2: " << globalStruct.f_name << std::endl;
return 0;
}
I hope somebody can help me I really dont get it how to do this :/
There is no way to directly access a local variable outside the block where it is defined. Because struct1 is an automatic variable, it is destroyed when put2struct returns, and no longer exists after that.
You can write a function that takes a FUNCTIONS by reference, and modify put2struct to call that function. That way you can access struct1 from a different cpp file:
void foo(FUNCTIONS&);
void put2struct()
{
FUNCTIONS struct1;
// do your thing
foo(struct1);
}
// another file
void foo(FUNCTIONS& object) {
// you have access to the object passed by reference
}

Data "member not declared in this scope"

I'm trying to create a vector which will store objects. I have added to the header file of the class as a private data member.
I am trying to initialize this vector as being empty (so that I can add objects to it later on in the program) but when I compile this program to test, this error is returned:
...error: '_bookingVector' was not declared in this scope|
I think the problem is with my initialization list on my default constructor(_bookingVector is obviously the vector):
Schedule::Schedule() : _bookingVector()
{ }
Is my syntax wrong? Or are vectors initialized differently?
Here is my code:
Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include "Booking.h"
#include <vector>
using namespace std;
class Schedule
{
public:
Schedule();
void AddBooking(int bday, int btime, int btrainer, int bid);
void RemoveBooking(int bday, int btime);
void DisplaySchedule();
void DisplayAvailableTimeSlots();
//For Testing
void DisplayDebug();
private:
vector<Booking> _bookingVector;
};
#endif // SCHEDULE_H
Schedule.cpp
#include "Schedule.h"
#include "Booking.h"
#include <vector>
#include <iostream>
Schedule::Schedule() : _bookingVector()
{ }
void AddBooking(int bday, int btime, int btrainer, int bid){
Booking bookingObject(bday, btime, btrainer, bid);
_bookingVector.push_back(bookingObject);
}
void DisplayDebug(){
for(int i = 0; i < _bookingVector.size(); ++i){
cout << _bookingVecotr[i] << endl;
}
}
I'm very eager to learn what I'm doing wrong and fix it.
The issue is not with the constructor, which looks fine if unnecessary1. The issue is that you have defined AddBooking and DisplayDebug as non-member functions, but these should be members in order to access other members of the class.
Modify the definitions to be in the scope of the Schedule class thus:
void Schedule::AddBooking(int bday, int btime, int btrainer, int bid) { ...
^^^^^^^^^^
void Schedule::DisplayDebug(){ ...
^^^^^^^^^^
Also, don't say using namespace std in a header file (I'd go further and say don't say it anywhere but there isn't universal agreement on that.)
1 Your default constructor does not do anything that the compiler-generated one wouldn't do. You can safely remove it.

Reference C++ struct object in another file?

I'm in the process of trying to make a game-in-progress more modular. I'd like to be able to declare a single array of all the room_t objects in the game (room_t rooms[]), store it in world.cpp and call it from other files.
The truncated code below does not work, but it's as far as I've gotten. I think I need to use extern but have not been able to find a method that works correctly. If I try and declare the array in the header file, I get a duplicate object error (as each file calls world.h, I'd assume).
main.cpp
#include <iostream>
#include "world.h"
int main()
{
int currentLocation = 0;
cout << "Room: " << rooms[currentLocation].name << "\n";
// error: 'rooms' was not declared in this scope
cout << rooms[currentLocation].desc << "\n";
return 0;
}
world.h
#ifndef WORLD_H
#define WORLD_H
#include <string>
const int ROOM_EXIT_LIST = 10;
const int ROOM_INVENTORY_SIZE = 10;
struct room_t
{
std::string name;
std::string desc;
int exits[ROOM_EXIT_LIST];
int inventory[ROOM_INVENTORY_SIZE];
};
#endif
world.cpp
#include "world.h"
room_t rooms[] = {
{"Bedroom", "There is a bed in here.", {-1,1,2,-1} },
{"Kitchen", "Knives! Knives everywhere!", {0,-1,3,-1} },
{"Hallway North", "A long corridor.",{-1,-1,-1,0} },
{"Hallway South", "A long corridor.",{-1,-1,-1,1} }
};
Just add extern room_t rooms[]; in your world.h file.
world.h
extern room_t rooms[];
The problem is that you're trying to reference a variable you've declared in the .cpp file. There's no handle on this outside of the scope of this file. In order to fix this, why not declare the variable in the .h file but have an Init function:
room_t rooms[];
void Init();
Then in the .cpp
void Init() {
// create a room_t and copy it over
}