簡體   English   中英

代碼無法編譯:錯誤C2099:初始化程序不是常量

[英]Code doesn't compile: error C2099: initializer is not a constant

我正在嘗試使用最初用C編寫的軟件在Visual C ++中編譯。 這是我到目前為止的代碼:

#include "timer.h"

FILE * timerFP = stdout;

int timerCount = 0;

double time_Master = 0.0;
static tsc_type tsc_Master;

void Timer_Start(void)
{
    readTSC(tsc_Master);
}

void Timer_Stop(void)
{
    tsc_type tsc_Master2;
    readTSC(tsc_Master2);
    time_Master += diffTSC(tsc_Master,tsc_Master2);
}

但Visual C ++給我以下錯誤:

error C2099: initializer is not a constant.

我該如何解決? 謝謝。

不能使用非常量值 (如stdout 初始化全局變量 您需要在main函數內部執行此操作(或者適合您的任何初始化函數):

FILE *timerFP;

int main(void) {
    timerFP = stdout;
    /* ... */
}

或者,您可以將其定義為函數:

FILE *timerFP(void) {
    return stdout;
}

典型的編譯器可以很容易地優化函數調用。

正如評論者已經指出的那樣, stdout不需要是常數。 例如,在MSVC ++ 2013中,它在%PROGRAMFILES(x86)%\\Microsoft Visual Studio 12.0\\VC\\include\\stdio.h第150行上定義如下:

#define stdout (&__iob_func()[1])

這意味着它涉及函數調用。 初始化器需要是編譯時常量, stdout不是。

(請注意,這在不同版本的MSVC ++之間會發生變化,因此您的版本可能會有所不同)

暫無
暫無

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

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