Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't clang -Wunused-member-function warn about an unused member function?

Tags:

I'm compiling a very basic program attempting to trigger output from -Wunused-member-function.

test.cpp:

#include <iostream>

class A {
    public:
    void foo() { std::cout << "Called foo" << std::endl; }
    void foo_unused() { std::cout << "Unused foo" << std::endl; }
};

int main() {
    A obj;
    obj.foo();
    return 0;
}

The output from the following command

clang++ -std=c++17 -Wall -Wunused -Wunused-member-function \
        -Wunused-function -Wunneeded-member-function \
        test.cpp -o test

unfortunately contained not even a single warning. I expected the compiler to warn about foo_unused not being used.

Is there a different behavior I'm missing here? Otherwise, why doesn't clang complain about the unused member function?

like image 316
Adam Avatar asked Jan 21 '19 11:01

Adam


1 Answers

You have to put the class in an anonymous namespace to make the warning appear:

namespace
{
class A {
    public:
    void foo() { std::cout << "Called foo" << std::endl; }
    void foo_unused() { std::cout << "Unused foo" << std::endl; }
};
}

You can see that now you have the warning: https://godbolt.org/z/15Buo-

The reason is that this version can activate clang checks on public methods as well, as you explicitely said that this class will not be accessible in another translation unit.

like image 142
Matthieu Brucher Avatar answered Oct 10 '22 23:10

Matthieu Brucher