简体   繁体   中英

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

I'm trying to get software originally written in C to compile in Visual C++. This is the code I have so far:

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

But Visual C++ gives me the following error:

error C2099: initializer is not a constant.

How do I fix this? Thank you.

You can't initialize a global variable with a non-constant value such as stdout . You need to do so inside your main function instead (or whatever initialization function is appropriate for your purposes):

FILE *timerFP;

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

Alternatively, you can define it as a function:

FILE *timerFP(void) {
    return stdout;
}

A typical compiler can quite easily optimize the function call away.

As commenters have already indicated, stdout is not required to be a constant. For example, in MSVC++ 2013 it is defined like this on line 150 of %PROGRAMFILES(x86)%\\Microsoft Visual Studio 12.0\\VC\\include\\stdio.h :

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

which means it involves a function call. Initializers need to be compile-time constants, and stdout is not.

(Note that this changes between different versions of MSVC++, so your version may be different)

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