Search code examples
c++includeglobal-variablesheader-files

How should I declare global variables in my C++ project?


I have two matrices as global variables. However, when I run my project, I get a apache Mach-O linker error in xCode that says that my global variables are declared more than once. I've determined the problem to be the placement of my global variables and the imports of the header files.

My svd.h is here:

#ifndef __netflix_project__svd__
#define __netflix_project__svd__

#include <stdio.h>
#include "dataManager.h"

const float GLOBAL_AVG_SET1 = 3.608609;
const float GLOBAL_AVG_SET2 = 3.608859;

const int TOTAL_USERS = 458293;
const int TOTAL_MOVIES = 17770;

double **user_feature_table = new double *[TOTAL_USERS];
double **movie_feature_table = new double *[TOTAL_MOVIES];


void initialize(int num_features);
void train();
double predictRating(int user, int movie); 




#endif /* defined(__netflix_project__svd__) */

My svd.cpp is here:

#include "svd.h"



void initialize(int num_features) {

    for(int i = 0; i < TOTAL_USERS; i++) {

        user_feature_table[i] = new double[num_features];

        for(int k = 0; k < num_features; k++) {
            user_feature_table[i][k] = GLOBAL_AVG_SET2 / num_features;
        }
    }

    for(int i = 0; i < TOTAL_MOVIES; i++) {

        movie_feature_table[i] = new double[num_features];

        for(int k = 0; k < num_features; k++) {
            movie_feature_table[i][k] = GLOBAL_AVG_SET2 / num_features;
        }
    }
}

My main.cpp looks like this:

#include <iostream>
#include "svd.h"






int main(int argc, const char * argv[]) {

    // Parse file and store test points as testPoint objects
    std::vector<testPoint*> dataSet = fillTestPoints();


    // Get global average of data set

    /*
    double avg = getGlobalAverage(dataSet);
    printf("%f", avg);
     */
    initialize(30);

    for(int i = 0; i < TOTAL_USERS; i++) {
        printf("%f\n", user_feature_table[i][0]);
    }

    return 0;
}

I ran into this problem before, but fixed it by taking out the global variables. However, I do need to optimize this code, and using global variables is the way to do it so I do need to figure this out. Thanks!


Solution

  • In header file, only declare them.

    extern const float GLOBAL_AVG_SET1;
    extern const float GLOBAL_AVG_SET2;
    
    extern const int TOTAL_USERS;
    extern const int TOTAL_MOVIES;
    
    extern double **user_feature_table;
    extern double **movie_feature_table;
    

    In one of your .cpp files, define and initialize them:

    const float GLOBAL_AVG_SET1 = 3.608609;
    const float GLOBAL_AVG_SET2 = 3.608859;
    
    const int TOTAL_USERS = 458293;
    const int TOTAL_MOVIES = 17770;
    
    double **user_feature_table = new double *[TOTAL_USERS];
    double **movie_feature_table = new double *[TOTAL_MOVIES];