静的ライブラリと共有ライブラリの整理 - その3 -

静的ライブラリ・共有ライブラリ作成時の注意点

※ 他にいい方法があるかもしれないのでご参考程度.
C++ で静的ライブラリ・共有ライブラリを作成する際は関数に extern "C" をつけてビルドする必要がある.しかしながら,extern "C" をつけてビルドしているためオーバーロード等が使用できない.
(参考: 静的ライブラリと共有ライブラリの整理 - その2 - - kawa0810の日記)

解決策

  • 静的ライブラリ
    1. extern "C" をつけて静的ライブラリを作成する
    2. 呼び出し先のヘッダーファイルなどで作成したライブラリの関数をオーバーロードさせる.
    • //cmath も同様の方法で呼び出しをしている模様.
  • 共有ライブラリ
    • 特に解決策なし.
    • 静的ライブラリと同様にラッパー関数を用意するくらい (?).

静的ライブラリにするコード

  • ヘッダーファイル: hoge.h
#ifndef _HH_HOGE_
#define _HH_HOGE_

//extern "C" がないと関数名が変更されるのでリンクできなくなる
extern "C" void builtin_test_void(void);
extern "C" void builtin_test_int(int);
extern "C" void builtin_test_double(double);

inline void test(void){ builtin_test_void(); } 
inline void test(int __x){ builtin_test_int(__x); }
inline void test(double __x){ builtin_test_double(__x); }

#endif
  • ライブラリにする関数: hoge.cpp
//hoge.cpp
#include <iostream>

//extern "C" がないと関数名が変更されるのでリンクできなくなる
extern "C" void builtin_test_void(void);
extern "C" void builtin_test_int(int);
extern "C" void builtin_test_double(double);

void builtin_test_void(void){
  std::cout << "This function is void" << std::endl;
}

void builtin_test_int(int const a){  
  std::cout << "This function is int(" << a << ")" << std::endl;
}

void builtin_test_double(double const a){  
  std::cout << "This function is double(" << a << ")" << std::endl;
}
  • 静的ライブラリの作成方法
$ g++-mp-4.8 hoge.cpp -c
$ ar r libhoge.a hoge.o

静的ライブラリの使用方法

使用方法
#include "hoge.h"

int main(void){

  test();

  int x = 123;
  test(x);

  double y = 3.12;
  test(y);

  return 0;
}
コンパイル方法と実行結果
$ g++-mp-4.8 main.cpp -L ./ -l hoge
$ ./a.out 
This function is void
This function is int(123)
This function is double(3.12)