Prevent compiler from removing methods if methods are declared inside class

3692 views c++
8

Disclaimer:

I am not interested in opinions about whether the following style is "good practice" or not. I'm searching an answer / a way to get around the problem.

Problem:

I am compiling a class within a cpp file. The compile process strips away my method definitions, that it thinks are "unused". Is there any way to prevent that? (See example below Development Environment)

Development Environment:

I'm using g++ --std=c++98 at the moment. A perfect solution is would be available on all c++98-standard compilers and newer.

Example:

example1.cpp

#include <stdio.h> 

class Example1{
    public: 
    void print(){printf("helloWorld");};

};

Compiling,assemble and link that file does not create the print() method. (g++ --std=c++98 example1.cpp main.cpp, where main.cpp simply calls the print method.)

Compiling this (no linking, g++ --std=c++98 -S ) will output:

example1.s

.file   "example1.cpp"
    .text
    .ident  "GCC: (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008"
    .section    .note.GNU-stack,"",@progbits
    .section    .note.gnu.property,"a"
    .align 8
    .long    1f - 0f
    .long    4f - 1f
    .long    5
0:
    .string  "GNU"
1:
    .align 8
    .long    0xc0000002
    .long    3f - 2f
2:
    .long    0x3
3:
    .align 8
4:

There is clearly no print() method generated here.

Not nice Workaround

I can make the compiler generate the method, if I use it in the same file (see code below). However, I'm searching for a nicer solution. Maybe compiler options?

example1.cpp

#include <stdio.h> 

class Example1{
    public: 
    void print(){printf("helloWorld");};

};

// Create a function outside the class, that uses print().
// That way, print will be generated.
void foo(){
    Example1 ex;
    ex.print();
}

answered question

I am not sure what the issue is. You just need to define the function outside the class definition, because function definitions inside the class definition are always inline, so the compiler is not required to emit the definition if it isn't used in the same translation unit.

1 Answer

13

From Here

You can create a false reference to the debugging function that cannot be optimized out. You do this by passing a pointer to the debugging function to a helper function outside your module that doesn’t do anything interesting. Since the helper function is not in your module, the compiler doesn’t know that the helper function doesn’t do anything, so it cannot optimize out the debugging function.

struct ForceFunctionToBeLinked { 
    ForceFunctionToBeLinked(const void *p) { SetLastError(PtrToInt(p)); }
 };

 ForceFunctionToBeLinked forceTestMe(TestMe);

posted this

Have an answer?

JD

Please login first before posting an answer.