GCC在一台计算机上编译而在另一台计算机上编译时给出错误

gcc gives an error when compiling on one computer but not another

本文关键字:一台 编译 计算机 出错 错误 GCC      更新时间:2023-10-16

我在两台Ubuntu电脑上编译了一个程序。两者都运行14.04,可能是gcc的相同版本。但是当我在一台计算机上编译它时,我得到了错误

warning: format ‘%i’ expects argument of type ‘int’, but argument 4 
has type ‘std::vector<colorgrad>::size_type {aka long unsigned int}’ [-Wformat=]

我认为违规代码是

for (vector<colorgrad>::size_type i = 0; i < grad.size(); ++i) {
    fprintf(svgOut, "%s%i%s%f%srgb(%i, %i, %i)%sn", "<stop id="stop", i,"" offset="",grad.at(i).perc ,"" style="stop-color: ",grad.at(i).r, grad.at(i).g, grad.at(i).b, ";stop-opacity:1;" />" );
}

当我用"%lu"替换第一个"% I"时,错误就消失了,但是当我在另一台计算机上编译该代码时,gcc给出相反的错误,并且只会编译"% I"。

我如何让这段代码在两台计算机上编译,而不必每次切换计算机时都切换出"% I"??

如注释vector::size_t所述,取决于平台,可能是32位或64位和格式%zu管理。

或者,你可以这样写:
(我使用c++ 11, for-range,原始字符串(不必转义"),但它也可以在c++ 03中完成)

std::ofstream oss; // initialize it with correct value
std::size_t i = 0;
for (const auto& color : grad) {
    oss << R"(<stop id="stop)" << i << R"(" offset=")" << color.perc
        << R"(" style="stop-color: rgb()"
        << color.r << ", " << color.g << ", "<< color.b
        << R"();stop-opacity:1;" />)" "n"; // you may replace "n" by std::endl
    ++i;
}
相关文章: