Prevent compiler from removing methods if methods are declared inside class

3692 views c++


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.


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.



#include <stdio.h> 

class Example1{
    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:


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

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?


#include <stdio.h> 

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


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

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


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?


Please login first before posting an answer.