Search code examples
c++g++narrowing

G++ raise compile errors instead of warnings for narrowing conversions


I want to get compile errors instead of warnings for this code:

#include <iostream>

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

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

If I compile it with:

g++ test.cpp -o test

I have no errors.

But If I compile the same code with:

g++ test.cpp -o test -Wconversion

I got the following warning:

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;

I'm looking for a way to get compile errors instead of warnings only for this particular type of warning.

Obs.1: -Werror can make all warnings become errors but it is not what I am looking for

Obs.2: I'm using g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0


Solution

  • Use -Werror= to treat specific warnings as errors only:

    g++ test.cpp -o test -Werror=conversion