0

I am currently trying to enable A.cpp from A folder to use a function func() defined in B.cpp from B folder.

The top level Makefile shows: DEPENDS = ... B A ....

Although I know very little about Makefiles, my boss told me the above Makefile statement indicates some hierarchy and dependency of the entire project. So I could not directly call func() defined in B.cpp from A.cpp. And he said I was silly to try to copy the entire dependency from B folder to A folder earlier. At last, he suggested me to use "Call back function" in this situation.

Now my basic understand of "Call back function" is that I need to pass "func" as an argument (pointer to func()) to some functions in A.cpp. However, I don't quite understand the motivation of using "callback function" in my case and how to realize it.

Could anybody give me some instructions? Thanks :-)

So I did the following things:

/* Inside /A/A.h */ 
 typedef void(*PTR_FUNC_B)();
 void SetCB(PTR_FUNC_B fn);  

 /* Inside /A/A.cpp  */
 PTR_FUNC_B myFn;
 void SetCB(PTR_FUNC_B fn) {myFn = fn}
 some_func_of_A () {
       myFn()             // segmentation fault
 }

 /* Inside /B/B.cpp  */
 void func_b() {
    std::printf("Invoke callback function.");
 }
 void register_cb() {
    SetCB(func_b);
 } 

Is my understanding of callback functions correct? I am glad I can compile it successfully, but I got "segmentation fault accessing address 0".

  • You have conflated two bits of advice, I think. First write a small program all in one file to get a grasp on using [function pointers to implement call backs](http://stackoverflow.com/questions/2298242/callback-functions-in-c) ([also look into `std::function`.](http://en.cppreference.com/w/cpp/utility/functional/function) Very handy.) Once you have a grip on that, split the two sides of the program of into separate files and a header that describes the interface. Keep it all in one directory for now. Once you have that working, Split it into separate folders. Finally, dig into makefiles – user4581301 Dec 07 '16 at 01:12
  • @user4581301 Thanks for your response. I realize the order in Makefile is actually about header files: /B/B.h called /A/A.h, while /A/A.h does not call /B/B.h. So I did the following things: –  Dec 07 '16 at 22:16

0 Answers0