stub function will not be called when two nested functions in the same file
dsocer opened this issue · 6 comments
In the following example, test_stub will not be called. But test_stub will be call when fun1 and fun2 are in two diff files.
main.c:
int test_stub(int a){
return 0;
}
stub.set(fun1, test_stub);
fun2(1);
test.c:
fun1(int a){return a;}
fun2(int a){ return fun1(a);}
What are the compile options?
cmake
SET(CMAKE_DXX_FLAGS_DEFAULT "-O2")
SET(CMAKE_CXX_FLAGS_RELEASE "-O2")
SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -g")
It's optimized by the compiler.
main.cpp
#include"stub.h"
#include <iostream>
int fun1(int a);
int fun2(int a);
int test_stub(int a){
std::cout << "test_stub" << std::endl;
return 0;
}
int main(){
Stub stub;
stub.set(fun1, test_stub);
fun2(1);
return 0;
}
test.cpp
int fun1(int a){return a;}
int fun2(int a){ return fun1(a);}
- g++ -O2 test.cpp main.cpp -o main
objdump -d main | c++filt
00000000000015f0 <fun2(int)>:
15f0: f3 0f 1e fa endbr64
15f4: 89 f8 mov %edi,%eax
15f6: c3 retq
15f7: 66 0f 1f 84 00 00 00 nopw 0x0(%rax,%rax,1)
15fe: 00 00
- g++ test.cpp main.cpp -o main
objdump -d main | c++filt
00000000000013d9 <fun2(int)>:
13d9: f3 0f 1e fa endbr64
13dd: 55 push %rbp
13de: 48 89 e5 mov %rsp,%rbp
13e1: 48 83 ec 08 sub $0x8,%rsp
13e5: 89 7d fc mov %edi,-0x4(%rbp)
13e8: 8b 45 fc mov -0x4(%rbp),%eax
13eb: 89 c7 mov %eax,%edi
13ed: e8 d7 ff ff ff callq 13c9 <fun1(int)>
13f2: c9 leaveq
13f3: c3 retq
Thank for your answer. However, I still have the same issue with -O0. My functions are much more complex than the ones in the above example so the compiler cannot remove fun1.
Give me an example of a problem so I can analyze it.
I think the above example can show the issue. With the command: "g++ test.cpp main.cpp -o main" and "./main" has a seg fault.
But if I separate the two functions in different files test1.cpp and test2.cpp, then it works well.
test1.cpp
int fun1(int a){return a;}
test2.cpp
int fun1(int a);
int fun2(int a){ return fun1(a);}