c++methodscompilation

C++. How to know where a method/variable is defined? or how to ask the compiler about it?


In our very large framework, tracking down a bug in one package, I ended up on a call to a function.

This function is not defined in the package I'm working on, and a search over the package itself does not give me any clue about the place where that function is defined in the framework.

So apparently it's defined in another package somewhere inside the framework.

I have to know what this function exactly does, so I would like to "ask" the compiler where it is defined. ...because the package compiles fine, so the function must be defined somewhere! ;-)

How can do that?


Solution

  • You can "ask" the compiler (and/or linker) where it is defined by creating a second definition of that function.

    void foo();
    
    void foo() // function you are looking for
    {
    }
    
    void foo() // second definition to tease the compiler.
    {
    }
    

    Now the compiler will complain and give you a hint

    main.cpp: In function ‘void foo()’:
    main.cpp:7: error: redefinition of ‘void foo()’
    main.cpp:3: error: ‘void foo()’ previously defined here
    

    The linker will now complain and give you a hint.

    b.cpp:(.text+0x6): multiple definition of `foo()'
    

    Now you know the real `foo' is in b.cpp.

    But what if it is defined in a header file?

    main.cpp:

    #include "secret.h"
    
    void foo() // second definition to tease the compiler.
    {
    }
    

    secret.h:

    void foo() // function you are looking for
    {
    }
    

    Now the compiler will find it for you:

    main.cpp: In function ‘void foo()’:
    main.cpp:3: error: redefinition of ‘void foo()’
    secret.h:1: error: ‘void foo()’ previously defined here
    

    Now you know the real `foo' is defined in secret.h.