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();
}
Remarks (edit):
- Defining methods outside the class is no option.
Example1
is used inmain.cpp
as follows:
main.cpp
class Example1{
public:
void print();
};
int main(){
Example1 example;
example.print();
return 0;
}