0

编译器:Microsoft Visual C++ 2010 Express,SP1 项目属性:C/C++ 高级编译为:编译为 C 代码 (/TC)

信息:

error C2099: initializer is not a constant

显示错误的简单测试用例:

typedef struct
{
    char *stringP;
    int  lino;
} foo_t;


#define bad {static foo_t foo ={__FILE__,__LINE__};}
#define good {static foo_t foo ={"filename",10};}

int main()
{

    bad;        // error C2099: initializer is not a constant
    good;       // no error

    return 0;
}

这会产生C2099错误。此代码在 gcc 但不是 Visual C++ 2010 Express 下正确编译和链接(编译为 C 代码 - 即 /TC 选项)。

4

3 回答 3

0

Your code compiles well on my system (MS Visual Studio 2005).

You can preprocess your code to try finding the problem manually:

cl your_file.c /E > stuff.c

This generates a preprocessed file (you probably have to supply a whole lot more command-line options; you can copy-paste them from the project's Property Pages).

cl stuff.c

This should reproduce the problem. Then try looking at the code in stuff.c; if you don't see the problem immediately, try tweaking it (e.g. replacing complex things with 0) - this should hint on the problem.

(Since your system is much newer than mine, some details may be different, e.g. maybe the compiler on your system is called something other than cl, but the idea will probably work)

于 2011-03-15T21:38:06.810 回答
0

__LINE__启用“编辑并继续”调试数据库模式时,MSVC 编译器不会将宏识别为常量。如果您不关心“编辑并继续”,您可以切换到另一种数据库模式,问题应该会消失。

于 2012-07-26T15:50:42.510 回答
0

由于某种原因,Microsoft C 编译器无法将__LINE__预处理器宏识别为常量(大概是因为它逐行更改?),因此您不能使用它来初始化结构成员。

生成预处理的 .i 文件并没有真正的帮助,因为它生成的合法代码在__LINE__被替换为常量后编译得很好。显然,C 编译器并没有尝试编译相同的预处理输出。

你应该可以使用

foo.lino = __LINE__;

后来没有任何问题。这似乎是 Microsoft C 编译器的一个抱怨。我用过的其他 C 编译器似乎对__LINE__.

我能找到的唯一解决方法是将文件编译为 C++ 代码 (/Tp)。

于 2011-05-20T20:57:54.430 回答