Languages

Menu
Sites
Language
Using C++ classes in Static lib

Hi,

I have added some classes with methods and built the static lib.

How do we export these class methods for use by other lib's and exe's?

Say for example, inside the static lib there is a class,

Class A{

int mValue;

public:

A();

int AddNumbers(int a){

return (this->mVaue + a);

}

};

How do we call the AddNumbers method? Where should we add the "extern" keyword ??

Thanks.

Responses

2 Replies
pius lee

There is no difference public method with "extern" or not.

basically every default functions are extern function, so you don't write extern before the public method.

but if you want call some C++ function in C, use extern "C" for it.

// static_lib.h
class Foobar {
 public:
  Foobar() : mValue(321) {};
  int AddNumbers(int a);
 private:
  int mValue;
};


// static_lib_c.h
int asdf(int a);


// static_lib.cc
int Foobar::AddNumbers(int a) {
  return this->mValue + a;
}

static int static_a = 123;
extern "C" int asdf(int a) {
  return static_a + a;
}

// static_lib_test.cc
#include <static_lib.h>                                                         
                                                                                
int main() {                                                                    
  Foobar f;                                                                     
  int x = f.AddNumbers(123);                                                    
  printf("%d", x);                                                              
}                                                                               


// static_lib_test.c
#include <stdio.h>                                                              
                                                                                
#include <static_lib_c.h>                                                       
                                                                                
int main() {                                                                    
    printf("%d", asdf(321));                                                    
    return 0;                                                                   
}                                                                               

 

Sathya Priya R

Thank you!