Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: namespace conflict between extern "C" and class member

I stumbled upon a rather exotic c++ namespace problem:

condensed example:

 extern "C" {
 void solve(lprec * lp);
 }

 class A {
 public:
    lprec * lp;
    void solve(int foo);
 }

 void A::solve(int foo)
 {
     solve(lp);
 }

I want to call the c function solve in my C++ member function A::solve. The compiler is not happy with my intent:

  error C2664: 'lp_solve_ilp::solve' : cannot convert parameter 1 from 'lprec *' to 'int'

Is there something I can prefix the solve function with? C::solve does not work

like image 313
plaisthos Avatar asked Apr 24 '10 20:04

plaisthos


People also ask

Do namespaces have external linkage?

Global variables and functions in the global namespace are assumed to have the extern specifier by default, and hence have external linkage. This means they can be seen and used ("linked to", if you like) by code in other files, by default.

Can you use extern C in C?

By declaring a function with extern "C" , it changes the linkage requirements so that the C++ compiler does not add the extra mangling information to the symbol. This pattern relies on the presence of the __cplusplus definition when using the C++ compiler. If you are using the C compiler, extern "C" is not used.

Do C++ features are allowed in extern C block?

Not any C-header can be made compatible with C++ by merely wrapping in extern "C".

What is extern C block?

extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.


1 Answers

To call a function in the global namespace, use:

::solve(lp);

This is needed whether the function is extern "C" or not.

like image 131
interjay Avatar answered Sep 25 '22 13:09

interjay