LoginSignup
0
1

More than 3 years have passed since last update.

C++をCで使えるようにする

Posted at

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!
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1