[[maybe_unused]] attribute not working
Asked Answered
R

2

10

I am trying to ignore the unused parameter warning using the new c++17 attribute [[maybe_unused]], as below.

int main([[maybe_unused]] int argc, char** argv)
{
    //...
}

But I still get warning: unused parameter ‘argc’ [-Wunused-parameter] with the following additional warning.

warning: ‘maybe_unused’ attribute directive ignored [-Wattributes]

I'm using g++ (GCC) 7.2.0 with cmake-3.11.3. My compiler flags are as follows.

-std=c++17 -Wall -pedantic -Wextra -Weffc++

I remember using this attribute successfully before, but I have no idea why this is not working now. Could someone show what I am doing wrong here?

Rote answered 10/6, 2018 at 14:50 Comment(3)
This is C++. If you flat out don't use it just don't name it.Caterinacatering
That warning means that the compiler doesn't support [[maybe_unused]]. Works just fine on g++ 7.2 over here however: godbolt.org/g/7KnuDx Double check the compiler version, and the compiler flags that are actually used by the generated makefile. That said, as StoryTeller points out, [[maybe_unused]] is redundant in a function argument, since you can simply leave it unnamed instead.Japan
In current compilers the attribute works as expected: gcc.godbolt.org/z/csf4EzvzbXenia
E
0

You can suppress warning about unused variable this way:

int main(int /* argc */, char** argv)
{
    //...
}

or using following trick:

int main(int argc, char** argv)
{
    (void)argc;

    //...
}

In this case this code will work for earlier versions of C++ standard and even for pure C.

Etymologize answered 10/10, 2021 at 17:23 Comment(0)
E
0

I tried the code but did not receive any warnings.

  • main.cpp
#include <iostream>

int main([[maybe_unused]] int argc, [[maybe_unused]]char** argv)
{
    return 0;
}
  • CMakeLists.txt
cmake_minimum_required(VERSION 3.1)
project(example)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic -Weffc++)
endif()

add_executable(${PROJECT_NAME} main.cpp)
  • Build
cmake -B build
cd build
make

Note: You can also solve the problem by using (void) as a second method

g++ --version
g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
cmake --version
cmake version 3.22.1
Evalynevan answered 29/8, 2024 at 5:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.