use cpp in c

This commit is contained in:
Alexander Popov 2023-11-06 02:12:29 +03:00
parent 90a995543d
commit 9bdf3e5249
Signed by: iiiypuk
GPG Key ID: E47FE0AB36CD5ED6
1 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,92 @@
---
title: "⚙️ Использование C++ кода в Си"
date: 2023-11-06T01:29:12+03:00
draft: false
tags: [c, cpp, tutorial, development]
---
## Введение
В данном руководстве на паре простых примеров покажу,
как использовать в программе на Си код на языке C++.
## Реализация динамическй библиотеки
Напишем функцию `void f(int i)` на C++, которая выводит в терминал число.
```cpp
// lib.cpp
#include <iostream>
extern "C" void f(int);
void f(int i) {
std::cout << i << std::endl;
}
```
Программа на Си, которая вызывает функцию C++ `f()`:
```c
// main.c
void f(int i);
int main(void) {
f(13);
return 0;
}
```
Компиляция
```sh
g++ -fpic -shared src/lib.cpp -o libaaa.so
gcc src/main.c -L. -laaa -o app
# Запуск
LD_LIBRARY_PATH=. ./app
```
## Реализация статической библиотеки
Функция на C++, которая выводит в терминал `int`.
```cpp
// lib.cpp
#include <iostream>
extern "C" {
void print_cout(const char *str) {
std::cout << str << std::endl;
}
}
```
Программа на Си, которая вызывает функцию C++:
```c
// main.c
void print_cout(const char *);
int main(void) {
print_cout("hello world!");
return 0;
}
```
Компиляция
```sh
gcc -c src/main.c -o main.o
g++ -c src/e.cpp -o aaa.o
g++ -o app main.o aaa.o
# Запуск
./app
```
## Полезные ссылки
- [How to mix C and C++](https://isocpp.org/wiki/faq/mixing-c-and-cpp)
- [Creating a shared and static library with the GNU compiler (gcc)](https://renenyffenegger.ch/notes/development/languages/C-C-plus-plus/GCC/create-libraries/index)
- [Using Static C++ Library in C](https://cplusplus.com/forum/general/284264/)