Linking C compiled static library to C++ Program

后端 未结 2 1882
谎友^
谎友^ 2020-12-18 20:38

I tried to link a static library (compiled with gcc) to a c++ program and I got \'undefined reference\'. I used gcc and g++ version 4.6.3 on a ubuntu 12.04 server machine. F

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 20:53

    While the accepted answer is absolutely correct, I thought I'd just add an observation. Some editors have trouble with the open / close brace, and will indent the entire extern "C" scope in the header. If mylib.h is a key header for a library, you might consider:

    #if defined (__cplusplus)
    #define _MYLIB_INIT_DECL extern "C" {
    #define _MYLIB_FINI_DECL }
    #else
    #define _MYLIB_INIT_DECL
    #define _MYLIB_FINI_DECL
    #endif
    

    All other headers in mylib library, e.g., mylib_aux.h, can be of the form:

    #ifndef _MYLIB_AUX_H
    #define _MYLIB_AUX_H
    
    #include 
    
    _MYLIB_INIT_DECL
    
    ... header content ...
    
    _MYLIB_FINI_DECL
    
    #endif /* _MYLIB_AUX_H */
    

    Obviously, the names I'm using are arbitrary, but for multiple library headers, this approach has been useful to me.

提交回复
热议问题