简体   繁体   中英

Compiling Multiple C++, getting uninitialized Vectors

Rather than have all my code in one giant file, I'm splitting it up into multiple files. The idea is to have a vector of structs (Thing) in another file (World.cpp), and to be able to access them from Main.cpp. Below is the relevant code:

World.h:

#include <vector>
#include "Lab4.h"
using namespace std;

struct Thing {
   glm::vec3 pos;
};

void InitWorld();
void addThingToWorld(glm::vec3 Position);
Thing getThingAtIndex(int index);

World.cpp:

#include "World.h"

vector<Thing> world;

void InitWorld() {
    Thing t;
    t.pos = glm::vec3 (0.5, 0.0, 0.0);
    world.push_back(t);
}

void addThingToWorld(glm::vec3 Position) {
   Thing t;
   t.pos = Position;
   world.push_back(t);
}

Thing getThingAtIndex(int index) {
   world.at(index);
}

Main.cpp:

#include "Lab4.h"

void main() {
    InitWorld();
    Thing t = getThingAtIndex(0);
    prinf("%f %f %f\n", t.pos.x, t.pos.y, t.pos.z);
}

The problem is that the values printed out from main are either garbage or all zeros. The code works perfectly fine if I have it in one file. I've spent a few hours on this but I can't figure it out. I would like an explanation as to why the "world" vector doesn't print out "0.5 0.0 0.0".

You didn't return anything in

Thing getThingAtIndex(int index) {
   world.at(index);
}   // returns garbage !!

Please correct in:

Thing getThingAtIndex(int index) {
   return world.at(index);
}   // now returns something 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM