How to use C++ code in nginx

malzad nginx-forum at forum.nginx.org
Sun Sep 12 06:39:21 UTC 2021


Hi there,

I am trying to implement a load balancing module and need to use some c++
codes in it. I tried to run a demo as follows:

I have a cpp_library.h, a cpp_library.cpp and my_load_balancer_module.c.

cpp_library.h

            #ifndef C_BASE_CPP_LIBRARY_H
            #define C_BASE_CPP_LIBRARY_H
            
            #ifdef __cplusplus
            extern "C" {
            #endif
            
            int cpp_hello_world();
            
            #ifdef __cplusplus
            }
            #endif
            
            #endif //C_BASE_CPP_LIBRARY_H

cpp_library.cpp

            #include <iostream>
            #include "cpp_library.h"
            
            int cpp_hello_world() {
                return 0;
            }

my_load_balancer_module.c

            #include <ngx_config.h>
            #include <ngx_core.h>
            #include <ngx_http.h>
            #include "cpp_library.h"
            ........................................
            ........................................
            ........................................
            ........................................

And I enabled --with-ld-opt="-lstdc++". It complied without any errors. But
when I loaded the my_load_balancer_module in the nginx.conf and tried to
start nginx, I am getting the following error:

            nginx: [emerg] dlopen()
"/usr/local/Cellar/nginx/1.21.0/modules/my_load_balancer_module.so" failed  
                        
           
(dlopen(/usr/local/Cellar/nginx/1.21.0/modules/my_load_balancer_module.so,
10): Symbol not found: _cpp_hello_world
            Referenced from:
/usr/local/Cellar/nginx/1.21.0/modules/my_load_balancer_module.so
            Expected in: flat namespace
            in
/usr/local/Cellar/nginx/1.21.0/modules/my_load_balancer_module.so) in
/usr/local/etc/nginx/nginx.conf:4


I think I am messing up something since I have very limited knowledge of
C/C++. Can you please help to figure out how to do it correctly? Thanks in
advance.

Posted at Nginx Forum: https://forum.nginx.org/read.php?2,292378,292378#msg-292378



More information about the nginx mailing list