C++に関数を埋め込み、Cのプログラムからその関数を呼び出すことでC++をCで使えるようにしました。
導入
ファイル構成
├── build/
├── main.c
├── test.cpp
├── test.h
└── CMakeLists.txt
以下が各ソースコードです。
main.c
#include "test.h"
int main() {
print_cpp("hello cpp!");
}
test.cpp
#include "test.h"
#include <iostream>
void print_cpp(const char *s) {
std::cout << s << std::endl;
}
test.h
#ifdef __cplusplus
extern "C" {
#endif
void print_cpp(const char *s);
#ifdef __cplusplus
}
#endif
CMakeLists.txt
cmake_minimum_required (VERSION 3.13)
add_executable(Main test.cpp main.c)
実行方法
(1) ビルドフォルダに移動
terminal
cd build
(2) cmake実行(out-of-source ビルド)
terminal
cmake ..
make
補足:cmakeを使わずにg++でコンパイルすると以下のようになります。(C++のバージョンはC++11)
terminal
g++ -o Main -std=c++11 ../test.cpp ../main.c
(3) 生成された実行ファイル(Main)を実行
terminal
./Main
実行結果
ターミナル上にc++経由で出力することができました。
terminal
hello cpp!