簡體   English   中英

如何在C ++項目中聲明全局變量?

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

我有兩個矩陣作為全局變量。 但是,當我運行項目時,在xCode中出現了一個Apache Mach-O鏈接器錯誤,該錯誤表明我的全局變量被聲明了多次。 我確定問題出在我的全局變量的位置和頭文件的導入。

我的svd.h在這里:

#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__) */

我的svd.cpp在這里:

#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;
        }
    }
}

我的main.cpp看起來像這樣:

#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;
}

我之前遇到過這個問題,但是通過取出全局變量來解決了。 但是,我確實需要優化此代碼,並且使用全局變量是實現此目的的方法,因此我需要弄清楚這一點。 謝謝!

在頭文件中,僅聲明它們。

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;

在您的一個.cpp文件中,定義並初始化它們:

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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM