G++ 引发编译错误而不是缩小转换的警告

时间:2021-07-31 13:17:35

标签: c++ g++ narrowing

我想获得编译错误而不是此代码的警告:

#include <iostream>

int main(int argc, char ** argv)
{
    float a = 1.3f;
    int b = 2.0 * a;

    std::cout << b << "\n";
}

如果我编译它:

g++ test.cpp -o test

我没有错误。

但是如果我编译相同的代码:

g++ test.cpp -o test -Wconversion

我收到以下警告:

test.cpp: In function ‘int main(int, char**)’:
test.cpp:6:17: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion]
6 |     int b = 2.0 * a;

我正在寻找一种方法来获取编译错误而不是警告,仅针对这种特定类型的警告。

Obs.1:-Werror 可以使所有警告都变成错误,但这不是我想要的

Obs.2:我正在使用 g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

1 个答案:

答案 0 :(得分:5)

使用 -Werror= 仅将特定警告视为错误:

g++ test.cpp -o test -Werror=conversion
相关问题