My Function Doesn't Know My Struct Values (c++) - c++

I'm new to doing structs, so please bear with me if this turns out to be a dumb question. I have one header file and four .cpp files that all include it. I have a struct called ToDoLista and it has string nameIt and int DeadLine. Then I have the things whose type name I don't know that are like, the Soccer and DropOffMax and stuff.
ToDoLista Soccer, DropOffMax, CookDinner;
Soccer.DeadLine=6;
Soccer.nameIt="SOCCER";
//and so on, for a total of six, 3 ints and 3 strings definitions.
This struct seems to be finnicky if I try to move it around because if it's in the header it's included three times and it wont run due to 'multiply defined' whatever. If I put it in one of my three non-main cpp files, it seems that the struct won't work because some of it has to be defined in main(). So now it's in my main cpp file, but I have functions that use these values, and those functions are in my non-main cpp files, which as far as I know compile before the main one. To get around that, I put the struct declaration in the header, and the definitions in my main (I may have mis-worded that) AND THEN I say 'okay, run the function 'CheckItTwice'.
//MAIN
Soccer.DeadLine=6;
//and so on for all six, like before.
//ok, NOW run the fx.
CheckItTwice(Soccer.Deadline, Soccer.nameIt);
The issue here is that if I tell CheckItTwice to say, cout the string, or the int, it runs the program without errors, but returns nothing in the console where the cout should be, because apparently they haven't been defined yet, as far as the function is concerned. Why is this/do you know a way around this?

In order to avoid the "defined multiply" errors you need to define your struct in a header file, and put a #pragma once or #ifndef...etc block at the top. See this here.
Include the header file in any implementation (cpp) file you plan to use the struct in.
The line
ToDoLista Soccer, DropOffMax, CookDinner;
declares three instances of the struct ToDolista, called Soccer, DropOffMax, and CookDinner. They are not types, they are instances of a type, that type being ToDolista.
I can't comment on the contents of CheckItTwice() as you didn't provide them, but look here for guidance on using cout. You might want to consider passing the struct as one argument to this method, preferrably as a const reference.

Define the struct in your header and #include that header in the cpp files. In the header try adding
#pragma once
at the top of your header file. This is a Microsoft specific extension - documented here
The more portable version is to add
#ifndef _SOME_DEF_
#define _SOME_DEF_
struct ToDoLista {
string namit;
string project;
int status;
int speed;
int difficulty;
int priority;
int deadline;
}
#endif // _SOME_DEF_
Be sure to remove struct definition from the .cpp file.

I got this issue resolved using something I saw while searching desperately online: extern. it seems that if I put the declaraction in the header, the definition in a cpp, and then declare the object again in another cpp but with 'extern' before it, it works like a charm as far as keeping the values from the original definition.
Header.h
struct ToDoLista{
string namit;
string project;
int status;
int speed;
int difficulty;
int priority;
int deadline;
};
Side.cpp
ToDoLista Pushups, Tumblr, Laundry, CleanRoom, CleanHouse, Portfolio;
void CheckItTwice(int staytus, string name){
if(staytus==1){//not on the list
staytus==2;
cout << "hurry up and" << name << " okay?" << endl;
Main.cpp
extern ToDoLista Pushups, Tumblr, Laundry, CleanRoom, CleanHouse, Portfolio;
Pushups.namit = "Push Ups";
Pushups.status = 1;
Pushups.speed = 0;
Pushups.difficulty = 0;
Pushups.priority = 0;
Pushups.project = "Get Fit";
Pushups.deadline = 20131102;
CheckItTwice(Pushups.status,Pushups.namit);
This works for me, and I hope this 'answer' helps someone else.

Related

Use one globe variable in all cpp files.If one class of the cpp file changed the value,I want to access it from another class cpp file

I want to Use one globe variable in all cpp files.If one class of the cpp file changed the value,I want to access it from another class cpp file,which is the value that least modified by any other cpp class file.
str.h - global variable file
#ifndef MY_PROG
#define MY_PROG
extern char * myname;
#endif
class1.cpp
#include "str.h"
char * myname;
class class1
{
class1(){}
~class1(){}
void Setname1(char *name) { myname = name }
};
class2.cpp
#include "str.h"
char * myname;
class class2
{
class2(){}
~class2(){}
void setName(char *name) { myname = name }
};
class3.cpp
#include "str.h"
class class3
{
class3(){}
~class3(){}
char *GetData()
{
return myname;
}
};
main.cpp
#include "str.h"
int main()
{
class1 c1;
class2 c2;
c1.Setname1("XXXX");
c2.setname("YYYY");
class3 c3;
cout << c3.GetData;
}
when I execute the program, I need to get Last modified value that is "YYYY" .I am new to cpp, And also please tell me whether I used the extern keyword correctly.If not , please provide me the right procedure.
The essential in your problem is understanding the difference between declarations and definitions of variables (and types, functions etc. objects in C/C++)
extern char * myname; is a declaration. It makes myname visible to other pieces of code in the same file so that they can reference it.
char * myname; is a definition. Not only it makes myname visible, it also instructs the compiler to allocate space for it and to make its address known.
You can have as many declarations of the same variable in your code as you want, as long as they do not contradict each other. No so with definitions. If you define a thing two times, it would need to be assigned two addresses, and then how can other object files "understand" which address to use when referencing it? The same goes with the space allocated — what to do with the extra piece of it allocated? This is the error that you see.
To make the code work, have only one and exactly one definition of myname in exactly one file. It must not be a header file because it gets copied into multiple source files thus creating multiple definitions. It can be any other C++ file though.
In the rest of the files (or in a single header included in all of them) have multiple declarations of myname if it is referenced in a particular file. If not, you can omit it for a particular unit.
All this being said, it is considered to be a VERY BAD PRACTICE to communicate data between compilation units through global mutable shared variables. They make code a nightmare to debug and understand and impossible to parallelize. Nobody ever thinking getting money for the code they write should use them. Instead, the best approach would be to pass a mutable object as one of methods/functions argument. Details actually depend on the rest of your application.

Access global data structure

I'm new to C++ and trying to make a map that all the source files will be able to access. Here is a simplified version of the problematic code. Every header file has a header guard, I just didn't type them here.
// main.cpp
#include "client.hpp"
int main(void){
init();
search();
}
// util.cpp
#include "util.hpp"
std::map<int, STUDENT_TYPE> dataBase;
init(){
dataBase[0] = STUDENT_TYPE(14, 4.0);
// more students....
}
// util.hpp
#include <map>
struct STUDENT_TYPE{
int age;
int grade;
STUDENT_TYPE(int age, int grade) : age(age), grade(grade){}
};
extern std::map<int, STUDENT_TYPE> dataBase;
// client.cpp
#include "client.hpp"
void search(){
std::cout << dataBase[0].grade << std::endl;
}
// client.hpp
#include "util.hpp"
void search();
The problem is that the compiler failed to build at the search function. It gives a big chain of errors. The last error or the cause of all the error is that the constructor of STUDENT_TYPE require 2 fields while given 0. I suspect that client can't access the STUDENT_TYPE struct inside the dataBase. I don't how to fix it or exactly how it happened. I just want a big table of students that all the files in the program can access.
The compiler is telling you exactly what's wrong. Your student type doesn't have a default constructor and it's being used.
Why is it being used?
Because map::operator [] will create a default constructed instance to return if an entry doesn't yet exist for that key. Even if this never happens, the compiler still has to compile that branch and it can't here.
Two ways to fix:
Give your student type a meaningful default.
Don't use map::operator[]. Instead use map::find.
First solution; don't have a global data structure. There is normally no need at at all to have such a thing.
Secondly, understand what header guards do - they prevent the body of a header file being included in the same translation unit. They have no effect if the header file is included in multiple .cpp files.
Thirdly, when you post questions about problems here, post the full text of the error messages you are getting.

C++ make error: object_var has not been declared [duplicate]

This question already has answers here:
error: Class has not been declared despite header inclusion, and the code compiling fine elsewhere
(9 answers)
Closed 7 years ago.
You could have forgot to include problemclass.h from the file where you are using ProblemClass.
You could have misspelled the name of ProblemClass either in its own header file or in the place where you are using it. This can be
hard to spot if it is a capitalization error such as writing
Problemclass or problemClass instead of ProblemClass.
You could have copy-pasted your inclusion guard #defines from one header file to another and then forgot to change the defined names.
Then only the first of those two included header files would take
effect.
You could have placed ProblemClass in a namespace A, in which case you must refer to ProblemClass as A::ProblemClass if you are referring
to it from outside the namespace A.
You may be using templates and not expecting two-phase lookup to work the way it does.
You could have misspelled the file name in your include. The compiler would not report an error on that if you also have an old
version of that file under the misspelled name.
You could have made ProblemClass a macro that only gets defined after you include problemclass.h, in which case what you see as
ProblemClass gets replaced by something else by the macro
preprocessor.
You could have defined ProblemClass in a header file other than problemclass.h and then problemclass.h actually defines something
else.
The above was taken from another similar question, I found the points useful but none actually solved my problem, stated hereunder:
I'm creating a natural language processor for a robot, giving the software various objects to represent real world items in its environment (Blocks world for now), one of the objects defined in Block:
/*
* Block.h
*
* Created on: 11 Mar 2015
* Author: Edward
*/
#ifndef BLOCK_HPP_
#define BLOCK_HPP_
#include "typedefinitions.h"
#include "dynamixel.h"
#include "BasicRobotFunctions.hpp"
class Block {
public:
bool grounded;
//TODO position is a deprecated variable, replace with distance from
//pos position;
int number;
int distance;
int object_brightness;
Block(BasicRobotFunctions basic);
virtual ~Block();
void setBrightness(int brightness);
void setGrounded(bool ground);
//void setPosition(int x, int y);
void setDistance(int number);
void setNumber(int number);
//pos getPosition();
int getNumber();
int getDistance();
bool getGrounded();
int getBrightness();
int lookAround(BasicRobotFunctions basic);
};
#endif /* BLOCK_H_ */
with source file:
/*
* Block.cpp
*
* Created on: 11 Mar 2015
* Author: Edward
*/
#include "Block.hpp"
#define DEFAULT_PORTNUM 3 // COM3
#define DEFAULT_BAUDNUM 1 // 1Mbps
Block::Block(BasicRobotFunctions basic) {
grounded = false;
number = Block::lookAround(basic);
}
Block::~Block() {}
void Block::setGrounded(bool ground){
grounded = ground;
}
/*
void Block::setPosition(int x, int y){
position.x = x;
position.y = y;
}*/
void Block::setDistance(int dist){
distance = dist;
}
void Block::setNumber(int num){
number = num;
}
bool Block::getGrounded(){
return grounded;
}
/*
pos Block::getPosition(){
return position;
}*/
int Block::getNumber(){
return number;
}
int Block::getDistance(){
return distance;
}
int Block::getBrightness(){
return object_brightness;
}
//TODO Arrange function to incorporate Turn() in BasicRobotFunctions
int Block::lookAround(BasicRobotFunctions basic){
int num = 0;
dxl_initialize(DEFAULT_PORTNUM,DEFAULT_BAUDNUM);
for(int i = 0;i<360;i++){
dxl_write_word(11,32,-255);
dxl_write_word(11,30,200);
basic.Step(1);
dxl_write_word(11,32,255);
dxl_write_word(11,30,100);
if(dxl_read_byte(100,32) >= dxl_read_byte(100,52)){
num++;
}
}
dxl_terminate();
return num;
}
void Block::setBrightness(int bright){
object_brightness = bright;
}
I am however receiving the following compilation error from the constructor and from the turnAround(BasicRobotFunctions) method:
In file included from Robot.hpp:11,
from BasicRobotFunctions.hpp:12,
from main.cpp:8:
Block.hpp:23: error: expected `)' before 'basic'
Block.hpp:35: error: 'BasicRobotFunctions' has not been declared
make.exe: *** [main.o] Error 1
Having checked my other classes utilizing objects as variables I get the same error.
In response to the points in the quote:
- BasicRobotFunctions.hpp is included
- the class name is spelt the same in all different instances mentioning it
- I didn't copy paste any inclusion guard
- I didn't use any namespaces in the project
- Nor am I using any templates
- the file name isn't misspelled in my include
- I haven't defined any macros in the program
- I made sure every class was defined in its own header file
Is there any other issue my system could possibly have, any mistake I'm making or simply anything I'm doing which is bad programming practice here?
The cause of your problem:
You have a header file circular dependency problem.
main.cpp includes BasicRobotFunctions.hpp
which includes Robot.hpp
which includes Block.hpp
which includes BasicRobotFunctions.hpp.
If your header files are properly guarded against multiple inclusion (which it seems that they are), Block.hpp won't see the definitions of BasicRobotFunctions.hpp because it is already in the middle of including it.
How to spot the problem:
The source of this problem is apparent in the compilation error message and in your Block.hpp file.
The compiler is reporting an error in Block.hpp, and it is describing line by line how it got to that file via inclusions. The source to your Block.hpp file makes it clear that it is trying to include BasicRobotFunctions.hpp.
The fix:
In your case, you can modify your method signatures in Block.hpp to use a (perhaps constant) reference to the BasicRobotFunctions type, and then forward declare the type. This allows you to eliminate the dependency on the BasicRobotFunctions.hpp header file. (Block.cpp would likely need to include both Block.hpp and BasicRobotFunctions.hpp.)
//...
#include "typedefinitions.h"
#include "dynamixel.h"
class BasicRobotFunctions; // Forward declaration
//...
Block(const BasicRobotFunctions &basic);
//...
int lookAround(const BasicRobotFunctions &basic);
//...
You may be able to avoid this problem in the future by minimizing what headers are required to allow your header file to compile. This means your header file should:
Use forward declarations to types that are used.
Use references to forward declared types.
You can check that your header file has minimized its dependencies by making sure it compiles by itself. I accomplish this by including the header file first in a corresponding source file, and then make sure the source file compiles.
// Foo.cpp
#include "Foo.hpp"
//...
Well you can put a forward declaration before the class as
class BasicRobotFunctions;
class Block {
public:
bool grounded;
//TODO position is a ...
but this kind of error means that the #include "BasicRobotFunctions.hpp"
don't declare the BasicRobotFunctions. It's possible a trouble with code guards?
The circular inclusion can be solved using the forward declaration, putting correct guards in headers and moving some includes to source files.

how to use not yet defined datatypes in a header?

I am programming on linux using g++ and I often encounter the problem that I need to use a class or data type in a header file which I define later, either at a later point in the header or in another header file.
For instance look at this header file:
class example
{
mydatatype blabla;
};
struct mydatatype
{
int blablainteger;
char blablachar;
};
This will give error because mydatatype is used before its defined
so usually I change it like this:
struct mydatatype; // <-- class prototype
class example
{
mydatatype *blabla; // <-- now a pointer to the data type
// I will allocate the data during runtime with the new operator
};
struct mydatatype
{
int blablainteger;
char blablachar;
};
Now it works. I could often just put the definition above, or include the header which is needed, but I don't want to include headers in a header or juggle with the definition order, it always gets messy.
The solution I showed usually works, but now I have encountered a new phenomenon. This time the datatype is not a class but a typedef, I cant use prototypes for a typedef and I don't want to use the actual datatype which the typedef incorporates.. it's messy too.
Is there any solution to this?
Firstly, the solution you've thought of (prototype and pointer), is unneeded, and slower than just implementing it without the pointer.
The "proper" solution for this, would be creating seperate headers for each type, and then include them in your other header. That way it will always be defined! You can even make them so that they include eachother.
However, if you've ever opened a .h file provided by g++, you've most likely seen this at the start of the header:
#ifndef SOMETHING_H
#define SOMETHING_H
// Code
#endif /* SOMETHING_H */
This is to solve the issue of types redefining themselves.
If they weren't there, and you included the header file multiple times, the types would be redefined, and an error would be thrown. This makes it so that the types are always present, but never included twice.
I hope that helps!
Place each class/type in it's own header file, and then include the relevant header file in other headers where you need it. Use an inclusion guard in each header e.g.:
// SomeHeaderFile.h
#ifndef SOME_HEADER_FILE_H
#define SOME_HEADER_FILE_H
// code
#endif
I disagree that this is messy - it allows you have an organised structure to you project, it allows each class to operate independently of others and without worrying about order, and it's a good idea to place each class in it's own file anyway.
You could just define the class inside the other class like
template<class T>
class vertex {
private:
class edge {
public:
vertex<T> *to;
double weight;
edge() {
weight = INFINITY;
to = NULL;
};
} *paths;
T data;
unsigned nof_paths;
public:
vertex(T val) {
data = val;
paths = NULL;
nof_paths = 0;
}
void addPathTo(vertex<T>*&);
edge* getAllPaths() {
return paths;
};
};
Obviously this works for small classes... if your class is ENORMOUS you'll be better using separate header files like the other guys said.

Extern unnamed struct object definition

I got a global object of type "unnamed-struct" and i'm trying to define it. I don't want to pollute my global namespace with such useless type (it will be used only once).
Global.h
extern struct {
int x;
} A;
Is there any correct way to define such object?
I was trying this:
Global.cpp
struct {
int x;
} A = { 0 };
But VS2012 throws "error C2371: 'A' : redefinition; different basic types". Thanks.
One possible solution: create another file Global_A.cpp that does not include Global.h, and define A there. By the equivalent-definition rule this will be valid, as long as the anonymous struct definitions are equivalent.
This is still a bad idea, and most compilers will warn about it e.g. (gcc): warning: non-local variable `<anonymous struct> A' uses anonymous type.
There is no way to do just this simply because it would be error prone: some time in the future someone (probably even you) may want to modify this structure's definition and he might forget to do this in the header and source files accordingly. So you will have to invent a name for this structure and use its name the source file and leave its definition up to the header.
I don't know if this helps you, and this my first post... So take it easy.
I just ran into this issue and what I did was I added a function that manipulates the struct to the file that contained the anonymous struct. That way I can call that function from any file in my project, and it manipulates the values in the struct for me.
Here is an example:
header.c has this anonymous struct:
struct
{
char line1[80];
char line2[80];
char line3[80];
} header;
I want to manipulate those values in "interface.c" because I am making a command line interface in another file. My first instinct was to use an extern, but it seems like adding the following function to header.c is just as good or better (Some people discourage the use of externs when avoidable).
void changeHeaders(char *one, char *two, char *three);
void changeHeaders(char *one, char *two, char *three)
{
strcpy(header.line1, one);
printf("\nHeader 1: %s", header.line1);
strcpy(header.line2, two);
printf("\nHeader 2: %s", header.line2);
strcpy(header.line3, three);
printf("\nHeader 3: %s", header.line3);
}
Now as long as I include the prototype for that function I can manipulate those struct variables from any file by using that function. Hope that helps someone.