简体   繁体   中英

Removing C-style casts in C++ code under Android

I saw this post on SO: Is there a way of disabling the old c style casts in c++ , and was excited to apply -Wold-style-cast to my Android C++ code. I quickly ran into the following casts in stdio.h :

static __inline int __sputc(int _c, FILE *_p) {
    if (--_p->_w >= 0 || (_p->_w >= _p->_lbfsize && (char)_c != '\n'))
        return (*_p->_p++ = _c);
    else
        return (__swbuf(_c, _p));
}

The file stdio.h was included through a series of other includes starting from ostream . Should C++ library headers include C headers that do C style casts? Has anyone tried disabling C style casts under Android NDK?

Yes, it's perfectly valid for a C++ standard library header to include C headers.

If you want to get around this (without modifying the standard library code), you can disable the warnings before including the header then re-enable them using GCC Diagnostic Pragmas .

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <iostream>
#include <vector>
// etc.
#pragma GCC diagnostic pop

The push and pop are there so that you can maintain the state of the diagnostics before and after the #pragmas .

Of course, you'll need to do this everywhere that you include the standard headers. If you have a lot of places that include them then it might be best to "refactor" your includes so that all your headers include one single header, which in turn includes the standard headers with the diagnostic wrappers.

Yes, obviously C++ headers may include C headers. And the standard doesn't prohibit any header to perform a C-style cast. No, I haven't tried that feature. Personally I avoid using C-Style casts without aid of the compiler.

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