pure/const function attributes in different compilers - c++

pure is a function attribute which says that a function does not modify any global memory.
const is a function attribute which says that a function does not read/modify any global memory.
Given that information, the compiler can do some additional optimisations.
Example for GCC:
float sigmoid(float x) __attribute__ ((const));
float calculate(float x, unsigned int C) {
float sum = 0;
for(unsigned int i = 0; i < C; ++i)
sum += sigmoid(x);
return sum;
}
float sigmoid(float x) { return 1.0f / (1.0f - exp(-x)); }
In that example, the compiler could optimise the function calculate to:
float calculate(float x, unsigned int C) {
float sum = 0;
float temp = C ? sigmoid(x) : 0.0f;
for(unsigned int i = 0; i < C; ++i)
sum += temp;
return sum;
}
Or if your compiler is clever enough (and not so strict about floats):
float calculate(float x, unsigned int C) { return C ? sigmoid(x) * C : 0.0f; }
How can I mark a function in such way for the different compilers, i.e. GCC, Clang, ICC, MSVC or others?

GCC: pure/const function attributes
llvm-gcc: supports the GCC pure/const attributes
Clang: seems to support it (I tried on a simple example with the GCC style attributes and it worked.)
ICC: seems to adopt the GCC attributes (Sorry, only a forum post.)
MSVC: Seems not to support it. (discussion)
In general, it seems that almost all compilers support the GCC attributes. MSVC is so far the only compiler which does not support them (and which also doesn't have any alternative).

First, it's useful to note that "const" is a more strict version of
"pure", so "pure" can be used as a fallback if a compiler doesn't
implement "const".
As others have mentioned, MSVC doesn't really have anything similar,
but a lot of compilers have adopted the GCC syntax, including many
which don't define __GNUC__ (and some which sometimes do and
sometimes don't, depending on flags).
GCC supports
pure
since 2.96+, and
const
since 2.5.0, in case you feel like checking the version.
Clang supports both; you can use __has_attribute(pure) and
__has_attribute(const) to detect them, but it's probably fine to
just rely on clang setting __GNUC__. This also includes compilers
based on clang like emscripten and XL C/C++ 13+.
Intel C/C++ Compiler supports both, but their documentation is
terrible so I have no idea when they were added. 16.0+ is certainly
safe.
Oracle Developer Studio 12.2+ supports both.
ARM C/C++ Compiler 4.1+ (and possibly older) supports both
pure
and
const
IBM XL C/C++ since at least 10.1.
TI 8.0+
TI 7.3+
with --gcc (detected with __TI_GNU_ATTRIBUTE_SUPPORT__) supports both.
PGI doesn't document it (AFAICT), but both attributes work (or are
at least silently ignored). 17.10+ is safe, though they've probably
been acceptable for much longer.
Of these, clang always defines __GNUC__ and friends (currently to
4.2, IIRC). Intel defines __GNUC__ by default (though it can be
suppressed with -no-gcc) as does PGI in C++ mode (but not in C
mode). The others you'll have to check for manually.
Oracle Developer Studio has also supported pragmas since it was known
as Forte Developer
6. They're
used a bit differently since they require you to specify the function
name:
/* pure: */
#pragma does_not_write_global_data (funcname)
/* const; SPARC-only until 12.2 */
#pragma no_side_effect (funcname)
TI 6.0+ (at least) supports a #pragma FUNC_IS_PURE; pragma in C++
mode only. In C mode, it's #pragma FUNC_IS_PURE(funcname);.
Most of this can be hidden behind a macro, which is what I've done in
Hedley:
#if \
HEDLEY_GNUC_HAS_ATTRIBUTE(pure,2,96,0) || \
HEDLEY_INTEL_VERSION_CHECK(16,0,0) || \
HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
HEDLEY_TI_VERSION_CHECK(8,0,0) || \
(HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
HEDLEY_PGI_VERSION_CHECK(17,10,0)
# define HEDLEY_PURE __attribute__((__pure__))
#elif HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
# define HEDLEY_NO_RETURN _Pragma("FUNC_IS_PURE;")
#else
# define HEDLEY_PURE
#endif
#if HEDLEY_GNUC_HAS_ATTRIBUTE(const, 2, 5, 0) || \
HEDLEY_INTEL_VERSION_CHECK(16,0,0) || \
HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
HEDLEY_TI_VERSION_CHECK(8,0,0) || \
(HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
HEDLEY_PGI_VERSION_CHECK(17,10,0)
# define HEDLEY_CONST __attribute__((__const__))
#else
# define HEDLEY_CONST HEDLEY_PURE
#endif
This doesn't include the variants which would require the function
names as an argument, but it still covers the vast majority of
users, and it's safe to use everywhere.
If you don't want to use Hedley (it's a single public domain / CC0 header) it
shouldn't be too difficult to replace the internal version macros. If
you choose to do that, you should probably base your port on the
Hedley repo instead of this answer as I'm much more likely to keep it
up to date.

As an update for anyone reading this after all these years, starting with C++11 (and with continuous improvements with C++14, C++17 and C++20), the constexpr keyword was added to the language, letting you mark functions, methods, statements, templates, variables (pretty much everything) as absolutely and completely constant, allowing for nice optimization from the compiler.
constevel and constinit were also added in C++20 to further expand the compile-time capabilities of the language.

Related

Is it possible to use std::endian if it is available, otherwise do something else?

Since C++20 we can have:
constexpr bool is_little_endian = std::endian::native == std::endian::little;
I would like to have code that does this if it is available, otherwise does runtime detection. Is this possible?
Maybe the code would look like:
template<bool b = std_endian_exists_v> constexpr bool is_little_endian;
template<> constexpr bool is_little_endian<true> = std::endian::native == std::endian::little;
template<> constexpr bool is_little_endian<false> = runtime_detection();
I am aware that testing __cplusplus via preprocessor is possible, however compilers phase in C++20 support in various stages so this is not a reliable indicator in either direction.
I am aware that testing __cplusplus via preprocessor is possible, however compilers phase in C++20 support in various stages so this is not a reliable indicator in either direction.
Indeed! In fact, this is why we now have an entirely new method of detecting feature support for compilers that are in various stages of release: feature-test macros! If you look at SD-FeatureTest, there are large tables of macros corresponding to each language and library feature adopted into the standard, where each macro will be defined with the specified value once a feature is adopted.
In your specific case, you want __cpp_lib_endian.
Now the problem with library macros is that we started added them before we added a place to put them - which would be <version>. If you're on a compiler that has <version> (which would be gcc 9+, clang 7+ with libc++, and I don't know about MSVC), you can just include that. But it might not, so you might also have to try to include the correct header (in this case <bit>).
#if __has_include(<bit>)
# include <bit>
# ifdef __cpp_lib_endian
# define HAS_ENDIAN 1
# endif
#endif
#ifdef HAS_ENDIAN
constexpr bool is_little_endian = std::endian::native == std::endian::little;
#else
constexpr bool is_little_endian = /* ... figure it out ... */;
#endif
Although it might be better to do:
#ifdef HAS_ENDIAN
using my_endian = std::endian;
#else
enum class my_endian {
// copy some existing implementation
};
#endif
constexpr bool is_little_endian = my_endian::native == my_endian::little;

C++: cleanest practice to write an empty function body [duplicate]

I have a cross platform application and in a few of my functions not all the values passed to functions are utilised. Hence I get a warning from GCC telling me that there are unused variables.
What would be the best way of coding around the warning?
An #ifdef around the function?
#ifdef _MSC_VER
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal qrLeft, qreal qrTop, qreal qrWidth, qreal qrHeight)
#else
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal /*qrLeft*/, qreal /*qrTop*/, qreal /*qrWidth*/, qreal /*qrHeight*/)
#endif
{
This is so ugly but seems like the way the compiler would prefer.
Or do I assign zero to the variable at the end of the function? (which I hate because it's altering something in the program flow to silence a compiler warning).
Is there a correct way?
You can put it in "(void)var;" expression (does nothing) so that a compiler sees it is used. This is portable between compilers.
E.g.
void foo(int param1, int param2)
{
(void)param2;
bar(param1);
}
Or,
#define UNUSED(expr) do { (void)(expr); } while (0)
...
void foo(int param1, int param2)
{
UNUSED(param2);
bar(param1);
}
In GCC and Clang you can use the __attribute__((unused)) preprocessor directive to achieve your goal.
For example:
int foo (__attribute__((unused)) int bar) {
return 0;
}
C++17 now provides the [[maybe_unused]] attribute.
http://en.cppreference.com/w/cpp/language/attributes
Quite nice and standard.
C++17 Update
In C++17 we gain the attribute [[maybe_unused]] which is covered in [dcl.attr.unused]
The attribute-token maybe_unused indicates that a name or entity is possibly intentionally unused. It shall
appear at most once in each attribute-list and no attribute-argument-clause shall be present.
...
Example:
[[maybe_unused]] void f([[maybe_unused]] bool thing1,
[[maybe_unused]] bool thing2) {
[[maybe_unused]] bool b = thing1 && thing2;
assert(b);
}
Implementations should not warn that b is unused, whether or not NDEBUG is defined. —end example ]
For the following example:
int foo ( int bar) {
bool unused_bool ;
return 0;
}
Both clang and gcc generate a diagnostic using -Wall -Wextra for both bar and unused_bool (See it live).
While adding [[maybe_unused]] silences the diagnostics:
int foo ([[maybe_unused]] int bar) {
[[maybe_unused]] bool unused_bool ;
return 0;
}
see it live.
Before C++17
In C++11 an alternative form of the UNUSED macro could be formed using a lambda expression(via Ben Deane) with an capture of the unused variable:
#define UNUSED(x) [&x]{}()
The immediate invocation of the lambda expression should be optimized away, given the following example:
int foo (int bar) {
UNUSED(bar) ;
return 0;
}
we can see in godbolt that the call is optimized away:
foo(int):
xorl %eax, %eax
ret
Your current solution is best - comment out the parameter name if you don't use it. That applies to all compilers, so you don't have to use the pre-processor to do it specially for GCC.
An even cleaner way is to just comment out variable names:
int main(int /* argc */, char const** /* argv */) {
return 0;
}
gcc doesn't flag these warnings by default. This warning must have been turned on either explicitly by passing -Wunused-parameter to the compiler or implicitly by passing -Wall -Wextra (or possibly some other combination of flags).
Unused parameter warnings can simply be suppressed by passing -Wno-unused-parameter to the compiler, but note that this disabling flag must come after any possible enabling flags for this warning in the compiler command line, so that it can take effect.
A coworker just pointed me to this nice little macro here
For ease I'll include the macro below.
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*#unused#*/ x
#else
# define UNUSED(x) x
#endif
void dcc_mon_siginfo_handler(int UNUSED(whatsig))
macro-less and portable way to declare one or more parameters as unused:
template <typename... Args> inline void unused(Args&&...) {}
int main(int argc, char* argv[])
{
unused(argc, argv);
return 0;
}
Using preprocessor directives is considered evil most of the time. Ideally you want to avoid them like the Pest. Remember that making the compiler understand your code is easy, allowing other programmers to understand your code is much harder. A few dozen cases like this here and there makes it very hard to read for yourself later or for others right now.
One way might be to put your parameters together into some sort of argument class. You could then use only a subset of the variables (equivalent to your assigning 0 really) or having different specializations of that argument class for each platform. This might however not be worth it, you need to analyze whether it would fit.
If you can read impossible templates, you might find advanced tips in the "Exceptional C++" book. If the people who would read your code could get their skillset to encompass the crazy stuff taught in that book, then you would have beautiful code which can also be easily read. The compiler would also be well aware of what you are doing (instead of hiding everything by preprocessing)
I have seen this instead of the (void)param2 way of silencing the warning:
void foo(int param1, int param2)
{
std::ignore = param2;
bar(param1);
}
Looks like this was added in C++11
Lol! I dont think there is another question on SO that reveal all the heretics corrupted by Chaos better that this one!
With all due respect to C++17 there is a clear guideline in C++ Core Guidelines. AFAIR, back in 2009 this option was available as well as today. And if somebody says it is considered as a bug in Doxygen then there is a bug in Doxygen
First off the warning is generated by the variable definition in the source file not the header file. The header can stay pristine and should, since you might be using something like doxygen to generate the API-documentation.
I will assume that you have completely different implementation in source files. In these cases you can either comment out the offending parameter or just write the parameter.
Example:
func(int a, int b)
{
b;
foo(a);
}
This might seem cryptic, so defined a macro like UNUSED. The way MFC did it is:
#ifdef _DEBUG
#define UNUSED(x)
#else
#define UNUSED(x) x
#endif
Like this you see the warning still in debug builds, might be helpful.
Is it not safe to always comment out parameter names? If it's not you can do something like
#ifdef _MSC_VER
# define P_(n) n
#else
# define P_(n)
#endif
void ProcessOps::sendToExternalApp(
QString sAppName, QString sImagePath,
qreal P_(qrLeft), qreal P_(qrTop), qreal P_(qrWidth), qreal P_(qrHeight))
It's a bit less ugly.
Using an UNREFERENCED_PARAMETER(p) could work. I know it is defined in WinNT.h for Windows systems and can easily be defined for gcc as well (if it doesn't already have it).
UNREFERENCED PARAMETER(p) is defined as
#define UNREFERENCED_PARAMETER(P) (P)
in WinNT.h.
Use compiler's flag, e.g. flag for GCC:
-Wno-unused-variable
In C++11, this is the solution I'm using:
template<typename... Ts> inline void Unreferenced(Ts&&...) {}
int Foo(int bar)
{
Unreferenced(bar);
return 0;
}
int Foo2(int bar1, int bar2)
{
Unreferenced(bar1, bar2);
return 0;
}
Verified to be portable (at least on modern msvc, clang and gcc) and not producing extra code when optimizations are enabled.
With no optimization, the extra function call is performed and references to the parameters are copied to the stack, but there are no macros involved.
If the extra code is an issue, you can use this declaration instead:
(decltype(Unreferenced(bar1, bar2)))0;
but at that point, a macro provides better readability:
#define UNREFERENCED(...) { (decltype(Unreferenced(__VA_ARGS__)))0; }
This works well but requires C++11
template <typename ...Args>
void unused(Args&& ...args)
{
(void)(sizeof...(args));
}
You can use __unused to tell the compiler that variable might not be used.
- (void)myMethod:(__unused NSObject *)theObject
{
// there will be no warning about `theObject`, because you wrote `__unused`
__unused int theInt = 0;
// there will be no warning, but you are still able to use `theInt` in the future
}
I found most of the presented answers work for local unused variable only, and will cause compile error for unused static global variable.
Another macro needed to suppress the warning of unused static global variable.
template <typename T>
const T* UNUSED_VARIABLE(const T& dummy) {
return &dummy;
}
#define UNUSED_GLOBAL_VARIABLE(x) namespace {\
const auto dummy = UNUSED_VARIABLE(x);\
}
static int a = 0;
UNUSED_GLOBAL_VARIABLE(a);
int main ()
{
int b = 3;
UNUSED_VARIABLE(b);
return 0;
}
This works because no warning will be reported for non-static global variable in anonymous namespace.
C++ 11 is required though
g++ -Wall -O3 -std=c++11 test.cpp
void func(void *aux UNUSED)
{
return;
}
smth like that, in that case if u dont use aux it wont warn u
I don't see your problem with the warning. Document it in the method/function header that compiler xy will issue a (correct) warning here, but that theses variables are needed for platform z.
The warning is correct, no need to turn it off. It does not invalidate the program - but it should be documented, that there is a reason.

suppress warnings on multiple compiler builds

Is there a generic suppress warning that i can use?
The problem is that there are times i may build using one compiler version (gcc) and then i have a partner that uses some of the common things but uses a different compiler. So the warning # are different.
The only way i could think of doing was making a macro that was defined in a file that i would pass in some generic value:
SUPPRESS_WARNING_BEGIN(NEVER_USED)
//code
SUPPRESS_WARNING_END
then the file would have something like:
#if COMPILER_A
NEVER_USED = 245
#endif
#if COMPILER_B
NEVER_USED = 332
#endif
#define SUPPRESS_WARNING_BEGIN(x) /
#if COMPILER_A
//Compiler A suppress warning x
#endif
#if COMPILER_B
//Compiler B suppress warning x
#endif
#define SUPPRESS_WARNING_END /
#if COMPILER_A
// END Compiler A suppress warning
#endif
#if COMPILER_B
// END Compiler A suppress warning
#endif
Don't know if there is an easier way? Also i know ideally we all would just use the same compiler but that is unfortunately not an option. Just trying to find the least complicated way to support something like this and am hoping there is a simpler way then mentioned above.
thanks
There's no portable way to do that. Different compilers do it in different ways (e.g. #pragma warning, #pragma GCC diagnostic, etc.).
The easiest and best thing to do is to write code that does not generate any warnings with at compiler at any warning level.
If your goal is to suppress warnings about unused variables, I recommend using a macro:
#define UNUSED(x) ((void)sizeof(x))
...
void some_function(int x, int y)
{
// No warnings will be generated if x is otherwise unused
UNUSED(x);
....
}
The sizeof operator is evaluated at compile-time, and the cast to void produces no result, so any compiler will optimize the UNUSED statement away into nothing but consider the operand to be used.
GCC also has the unused attribute`:
// No warnings will be generated if x is otherwise unused
int x __attribute__((unused));

How to make a cross-platform c++ inline assembly language?

I hacked a following code:
unsigned long long get_cc_time () volatile {
uint64 ret;
__asm__ __volatile__("rdtsc" : "=A" (ret) : :);
return ret;
}
It works on g++ but not on Visual Studio.
How can I port it ?
What are the right macros to detect VS / g++ ?
#if defined(_MSC_VER)
// visual c
#elif defined(__GCCE__)
// gcce
#else
// unknown
#endif
My inline assembler skills are rusty, but it works like:
__asm
{
// some assembler code
}
But to just use rdtsc you can just use intrinsics:
unsigned __int64 counter;
counter = __rdtsc();
http://msdn.microsoft.com/en-us/library/twchhe95.aspx
The specific problem OP had aside: I found a way to define a macro that works for both syntax versions:
#ifdef _MSC_VER
# define ASM(asm_literal) \
__asm { \
asm_literal \
};
#elif __GNUC__ || __clang__
# define ASM(asm_literal) \
"__asm__(\"" \
#asm_literal \
"\" : : );"
#endif
Unfortunately, because the preprocessor strips newlines before macro expansion, you have to surround each assembly statement with this macro.
float abs(float x) {
ASM( fld dword ptr[x] );
ASM( fabs );
ASM( fstp dword ptr[x] );
return x;
}
But please be aware that GCC and clang use AT&T/UNIX assembly synax but MSVC usees Intel assembly syntax (couldn't find any official source though). But fortunately GCC/clang can be configured to use Intel syntax, too. Either use __asm__(".intel_syntax noprefix");/ __asm__(".att_syntax prefix"); (be sure to reset the changes as it will affect all assembly generated from that point on, even the one generated by the compiler from the C source). This would leave us with a macro like this:
#ifdef _MSC_VER
# define ASM(asm_literal) \
__asm { \
asm_literal \
};
#elif __GNUC__ || __clang__
# define ASM(asm_literal) \
"__asm__(\".intel_syntax noprefix\");" \
"__asm__(\"" \
#asm_literal \
"\" : : );" \
"__asm__(\".att_syntax prefix\");"
#endif
Or you can also compile with GCC/clang using the -masm=intel flag, which switches the syntax globally.
There's a _MSC_VER macro in VC++ that is described as "Microsoft specific" in MSDN and presumably is not defined when code is compiled on other compilers. You can use #ifdef to determine what compiler it is and compile different code for gcc and VC++.
#ifdef _MSC_VER
//VC++ version
#else
//gcc version
#endif
Using the RDTSC instruction directly has some severe drawbacks:
The TSC isn't guaranteed to be synchronized on all CPUs, so if your thread/process migrates from one CPU core to another the TSC may appear to "warp" forward or backward in time unless you use thread/process affinity to prevent migration.
The TSC isn't guaranteed to advance at a constant rate, particularly on PCs that have power management or "C1 clock ramping" enabled. With multiple CPUs, this may increase the skew (for example, if you have one thread that is spinning and another that is sleeping, one TSC may advance faster than the other).
Accessing the TSC directly doesn't allow you to take advantage of HPET.
Using an OS timer interface is better, but still may have some of the same drawbacks depending on the implementation:
Linux: clock_gettime()
Windows: QueryPerformanceCounter()
Also note that Microsoft Visual C++ doesn't support inline assembly when targeting 64-bit processors, hence the __rdtsc() intrinsic that Virne pointed out.

How do I best silence a warning about unused variables?

I have a cross platform application and in a few of my functions not all the values passed to functions are utilised. Hence I get a warning from GCC telling me that there are unused variables.
What would be the best way of coding around the warning?
An #ifdef around the function?
#ifdef _MSC_VER
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal qrLeft, qreal qrTop, qreal qrWidth, qreal qrHeight)
#else
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal /*qrLeft*/, qreal /*qrTop*/, qreal /*qrWidth*/, qreal /*qrHeight*/)
#endif
{
This is so ugly but seems like the way the compiler would prefer.
Or do I assign zero to the variable at the end of the function? (which I hate because it's altering something in the program flow to silence a compiler warning).
Is there a correct way?
You can put it in "(void)var;" expression (does nothing) so that a compiler sees it is used. This is portable between compilers.
E.g.
void foo(int param1, int param2)
{
(void)param2;
bar(param1);
}
Or,
#define UNUSED(expr) do { (void)(expr); } while (0)
...
void foo(int param1, int param2)
{
UNUSED(param2);
bar(param1);
}
In GCC and Clang you can use the __attribute__((unused)) preprocessor directive to achieve your goal.
For example:
int foo (__attribute__((unused)) int bar) {
return 0;
}
C++17 now provides the [[maybe_unused]] attribute.
http://en.cppreference.com/w/cpp/language/attributes
Quite nice and standard.
C++17 Update
In C++17 we gain the attribute [[maybe_unused]] which is covered in [dcl.attr.unused]
The attribute-token maybe_unused indicates that a name or entity is possibly intentionally unused. It shall
appear at most once in each attribute-list and no attribute-argument-clause shall be present.
...
Example:
[[maybe_unused]] void f([[maybe_unused]] bool thing1,
[[maybe_unused]] bool thing2) {
[[maybe_unused]] bool b = thing1 && thing2;
assert(b);
}
Implementations should not warn that b is unused, whether or not NDEBUG is defined. —end example ]
For the following example:
int foo ( int bar) {
bool unused_bool ;
return 0;
}
Both clang and gcc generate a diagnostic using -Wall -Wextra for both bar and unused_bool (See it live).
While adding [[maybe_unused]] silences the diagnostics:
int foo ([[maybe_unused]] int bar) {
[[maybe_unused]] bool unused_bool ;
return 0;
}
see it live.
Before C++17
In C++11 an alternative form of the UNUSED macro could be formed using a lambda expression(via Ben Deane) with an capture of the unused variable:
#define UNUSED(x) [&x]{}()
The immediate invocation of the lambda expression should be optimized away, given the following example:
int foo (int bar) {
UNUSED(bar) ;
return 0;
}
we can see in godbolt that the call is optimized away:
foo(int):
xorl %eax, %eax
ret
Your current solution is best - comment out the parameter name if you don't use it. That applies to all compilers, so you don't have to use the pre-processor to do it specially for GCC.
An even cleaner way is to just comment out variable names:
int main(int /* argc */, char const** /* argv */) {
return 0;
}
gcc doesn't flag these warnings by default. This warning must have been turned on either explicitly by passing -Wunused-parameter to the compiler or implicitly by passing -Wall -Wextra (or possibly some other combination of flags).
Unused parameter warnings can simply be suppressed by passing -Wno-unused-parameter to the compiler, but note that this disabling flag must come after any possible enabling flags for this warning in the compiler command line, so that it can take effect.
A coworker just pointed me to this nice little macro here
For ease I'll include the macro below.
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*#unused#*/ x
#else
# define UNUSED(x) x
#endif
void dcc_mon_siginfo_handler(int UNUSED(whatsig))
macro-less and portable way to declare one or more parameters as unused:
template <typename... Args> inline void unused(Args&&...) {}
int main(int argc, char* argv[])
{
unused(argc, argv);
return 0;
}
Using preprocessor directives is considered evil most of the time. Ideally you want to avoid them like the Pest. Remember that making the compiler understand your code is easy, allowing other programmers to understand your code is much harder. A few dozen cases like this here and there makes it very hard to read for yourself later or for others right now.
One way might be to put your parameters together into some sort of argument class. You could then use only a subset of the variables (equivalent to your assigning 0 really) or having different specializations of that argument class for each platform. This might however not be worth it, you need to analyze whether it would fit.
If you can read impossible templates, you might find advanced tips in the "Exceptional C++" book. If the people who would read your code could get their skillset to encompass the crazy stuff taught in that book, then you would have beautiful code which can also be easily read. The compiler would also be well aware of what you are doing (instead of hiding everything by preprocessing)
I have seen this instead of the (void)param2 way of silencing the warning:
void foo(int param1, int param2)
{
std::ignore = param2;
bar(param1);
}
Looks like this was added in C++11
Lol! I dont think there is another question on SO that reveal all the heretics corrupted by Chaos better that this one!
With all due respect to C++17 there is a clear guideline in C++ Core Guidelines. AFAIR, back in 2009 this option was available as well as today. And if somebody says it is considered as a bug in Doxygen then there is a bug in Doxygen
First off the warning is generated by the variable definition in the source file not the header file. The header can stay pristine and should, since you might be using something like doxygen to generate the API-documentation.
I will assume that you have completely different implementation in source files. In these cases you can either comment out the offending parameter or just write the parameter.
Example:
func(int a, int b)
{
b;
foo(a);
}
This might seem cryptic, so defined a macro like UNUSED. The way MFC did it is:
#ifdef _DEBUG
#define UNUSED(x)
#else
#define UNUSED(x) x
#endif
Like this you see the warning still in debug builds, might be helpful.
Is it not safe to always comment out parameter names? If it's not you can do something like
#ifdef _MSC_VER
# define P_(n) n
#else
# define P_(n)
#endif
void ProcessOps::sendToExternalApp(
QString sAppName, QString sImagePath,
qreal P_(qrLeft), qreal P_(qrTop), qreal P_(qrWidth), qreal P_(qrHeight))
It's a bit less ugly.
Using an UNREFERENCED_PARAMETER(p) could work. I know it is defined in WinNT.h for Windows systems and can easily be defined for gcc as well (if it doesn't already have it).
UNREFERENCED PARAMETER(p) is defined as
#define UNREFERENCED_PARAMETER(P) (P)
in WinNT.h.
Use compiler's flag, e.g. flag for GCC:
-Wno-unused-variable
In C++11, this is the solution I'm using:
template<typename... Ts> inline void Unreferenced(Ts&&...) {}
int Foo(int bar)
{
Unreferenced(bar);
return 0;
}
int Foo2(int bar1, int bar2)
{
Unreferenced(bar1, bar2);
return 0;
}
Verified to be portable (at least on modern msvc, clang and gcc) and not producing extra code when optimizations are enabled.
With no optimization, the extra function call is performed and references to the parameters are copied to the stack, but there are no macros involved.
If the extra code is an issue, you can use this declaration instead:
(decltype(Unreferenced(bar1, bar2)))0;
but at that point, a macro provides better readability:
#define UNREFERENCED(...) { (decltype(Unreferenced(__VA_ARGS__)))0; }
This works well but requires C++11
template <typename ...Args>
void unused(Args&& ...args)
{
(void)(sizeof...(args));
}
You can use __unused to tell the compiler that variable might not be used.
- (void)myMethod:(__unused NSObject *)theObject
{
// there will be no warning about `theObject`, because you wrote `__unused`
__unused int theInt = 0;
// there will be no warning, but you are still able to use `theInt` in the future
}
I found most of the presented answers work for local unused variable only, and will cause compile error for unused static global variable.
Another macro needed to suppress the warning of unused static global variable.
template <typename T>
const T* UNUSED_VARIABLE(const T& dummy) {
return &dummy;
}
#define UNUSED_GLOBAL_VARIABLE(x) namespace {\
const auto dummy = UNUSED_VARIABLE(x);\
}
static int a = 0;
UNUSED_GLOBAL_VARIABLE(a);
int main ()
{
int b = 3;
UNUSED_VARIABLE(b);
return 0;
}
This works because no warning will be reported for non-static global variable in anonymous namespace.
C++ 11 is required though
g++ -Wall -O3 -std=c++11 test.cpp
void func(void *aux UNUSED)
{
return;
}
smth like that, in that case if u dont use aux it wont warn u
I don't see your problem with the warning. Document it in the method/function header that compiler xy will issue a (correct) warning here, but that theses variables are needed for platform z.
The warning is correct, no need to turn it off. It does not invalidate the program - but it should be documented, that there is a reason.