Невозможно вызвать функцию C ++ из кода C

Я новичок в микшировании C & C ++ код. Понял необходимость экстерна & __cplusplus директивы после прочтения некоторых SO ссылок & онлайн чтение.
Не уверен, почему я получаю ошибку. Я что-то пропустил ?

Заголовок C ++: cppexh.h

#include <iostream>

#ifdef __cplusplus
extern "C" {
#endif

void Callme(int a);

#ifdef __cplusplus
}
#endif

C ++ Source

#include "cppexh.h"
void Callme(int a)
{
std::cout << "Val is " << a << std::endl;
}

Код C, вызывающий функцию C ++

#include <stdio.h>
#include "cppexh.h"
int main()
{
CallMe(2);
retun 1;
}

Но я получаю ошибки компиляции:

1>------ Rebuild All started: Project: CProject, Configuration: Debug Win32 ------
1>  Ccode.c
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xtgmath.h(214): warning C4602: #pragma pop_macro : 'new' no previous #pragma push_macro for this identifier
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xtgmath.h(215): warning C4193: #pragma warning(pop) : no matching '#pragma warning(push)'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xtgmath.h(216): warning C4161: #pragma pack(pop...) : more pops than pushes
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(23): error C2061: syntax error : identifier 'abs'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(23): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(23): error C2061: syntax error : identifier 'acos'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(23): error C2061: syntax error : identifier 'asin'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(24): error C2061: syntax error : identifier 'atan'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(24): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(24): error C2061: syntax error : identifier 'atan2'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(24): error C2061: syntax error : identifier 'ceil'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(25): error C2061: syntax error : identifier 'cos'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(25): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(25): error C2061: syntax error : identifier 'cosh'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(25): error C2061: syntax error : identifier 'exp'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(26): error C2061: syntax error : identifier 'fabs'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(26): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(26): error C2061: syntax error : identifier 'floor'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(26): error C2061: syntax error : identifier 'fmod'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(27): error C2061: syntax error : identifier 'frexp'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(27): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(27): error C2061: syntax error : identifier 'ldexp'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(27): error C2061: syntax error : identifier 'log'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(28): error C2061: syntax error : identifier 'log10'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(28): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(28): error C2061: syntax error : identifier 'modf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(28): error C2061: syntax error : identifier 'pow'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(29): error C2061: syntax error : identifier 'sin'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(29): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(29): error C2061: syntax error : identifier 'sinh'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(29): error C2061: syntax error : identifier 'sqrt'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(30): error C2061: syntax error : identifier 'tan'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(30): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(30): error C2061: syntax error : identifier 'tanh'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(32): error C2061: syntax error : identifier 'acosf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(32): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(32): error C2061: syntax error : identifier 'asinf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(33): error C2061: syntax error : identifier 'atanf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(33): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(33): error C2061: syntax error : identifier 'atan2f'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(33): error C2061: syntax error : identifier 'ceilf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(34): error C2061: syntax error : identifier 'cosf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(34): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(34): error C2061: syntax error : identifier 'coshf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(34): error C2061: syntax error : identifier 'expf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(35): error C2061: syntax error : identifier 'fabsf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(35): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(35): error C2061: syntax error : identifier 'floorf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(35): error C2061: syntax error : identifier 'fmodf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(36): error C2061: syntax error : identifier 'frexpf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(36): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(36): error C2061: syntax error : identifier 'ldexpf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(36): error C2061: syntax error : identifier 'logf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(37): error C2061: syntax error : identifier 'log10f'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(37): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(37): error C2061: syntax error : identifier 'modff'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(37): error C2061: syntax error : identifier 'powf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(38): error C2061: syntax error : identifier 'sinf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(38): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(38): error C2061: syntax error : identifier 'sinhf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(38): error C2061: syntax error : identifier 'sqrtf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(39): error C2061: syntax error : identifier 'tanf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(39): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(39): error C2061: syntax error : identifier 'tanhf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(41): error C2061: syntax error : identifier 'acosl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(41): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(41): error C2061: syntax error : identifier 'asinl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(42): error C2061: syntax error : identifier 'atanl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(42): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(42): error C2061: syntax error : identifier 'atan2l'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(42): error C2061: syntax error : identifier 'ceill'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(43): error C2061: syntax error : identifier 'cosl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(43): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(43): error C2061: syntax error : identifier 'coshl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(43): error C2061: syntax error : identifier 'expl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(44): error C2061: syntax error : identifier 'fabsl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(44): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(44): error C2061: syntax error : identifier 'floorl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(44): error C2061: syntax error : identifier 'fmodl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(45): error C2061: syntax error : identifier 'frexpl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(45): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(45): error C2061: syntax error : identifier 'ldexpl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(45): error C2061: syntax error : identifier 'logl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(46): error C2061: syntax error : identifier 'log10l'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(46): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(46): error C2061: syntax error : identifier 'modfl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(46): error C2061: syntax error : identifier 'powl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(47): error C2061: syntax error : identifier 'sinl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(47): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(47): error C2061: syntax error : identifier 'sinhl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(47): error C2061: syntax error : identifier 'sqrtl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(48): error C2061: syntax error : identifier 'tanl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(48): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(48): error C2061: syntax error : identifier 'tanhl'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(50): error C2054: expected '(' to follow 'using'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(50): error C2061: syntax error : identifier 'using'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(52): error C2061: syntax error : identifier 'acosh'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(52): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(52): error C2061: syntax error : identifier 'asinh'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(52): error C2061: syntax error : identifier 'atanh'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(53): error C2061: syntax error : identifier 'cbrt'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(53): error C2059: syntax error : ';'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(53): error C2061: syntax error : identifier 'erf'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(53): error C2061: syntax error : identifier 'erfc'
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\cmath(53): fatal error C1003: error count exceeds 100; stopping compilation
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

ВЕРСИЯ 2 КОДА

РЕДАКТИРОВАТЬ КОДЕКС, КОТОРЫЙ РЕШЕН ВОПРОСЫ КОМПИЛЯЦИИ, НО ОШИБКА ССЫЛКИ ЕЩЕ ОСТАЕТСЯ

#ifdef __cplusplus
#include <iostream>
#endif

#ifdef __cplusplus
extern "C" {
#endif

void Callme(int a);

#ifdef __cplusplus
}
#endif

МОЙ КОД C ++ — СТАТИЧЕСКАЯ БИБЛИОТЕКА.

ОШИБКА ССЫЛКИ

1>------ Rebuild All started: Project: CProject, Configuration: Debug Win32 ------
1>  Ccode.c
1>c:\users\ngk\documents\ccg\vsprojects\expapp\cproject\ccode.c(6): warning C4013: 'CallMe' undefined; assuming extern returning int
1>Ccode.obj : error LNK2019: unresolved external symbol _CallMe referenced in function _main
1>C:\Users\ngk\Documents\CCG\VSprojects\ExpApp\Debug\CProject.exe : fatal error LNK1120: 1 unresolved externals
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

2

Решение

Переехать

#include <iostream>

в исходный файл с ++.

Компилятор C не может иметь дело с кодом C ++ в этом заголовке, если он включен из main() переводческий блок.

Также позаботьтесь об использовании одинаковых имен функций и типов параметров для объявления, определения и вызова. Оба компилятора чувствительны к регистру.

CallMe(int) не то же самое, что Callme(int),


Что касается вашего редактирования:

Убедитесь, что вы правильно добавили статическую библиотеку в свой проект.

8

Другие решения

Мне очень повезло, что мне пришлось объединить основную программу на C, называемую доморощенным C ++.

Что касается вашей первой проблемы (как уже говорили другие), переместите #include <iostream> в ваш файл C ++.

Что касается вашей проблемы с линкером:

Это может (или не может) быть подобной вещью, которая заставила меня вращать мои колеса. Но об этом нужно помнить, потому что это безумно глупо.

Предполагая, что вы строите свой код C ++ в DLL, и отдельно компилируете свой код C в исполняемый файл, который вызывает библиотеку DLL:

В Visual Studio Неуправляемый C, DLL не удаляются из папки «Release» так, как в Удалось C ++. Вы должны физически переместить
каждая новая DLL в папке «Release» вашей прикладной программы
время внесения изменений в вашу DLL.

Я узнал, как бороться с обновлением DLL в Удалось C ++, где все, что вам нужно сделать (в папке вашей прикладной программы), это очистить вашу старую DLL «библиотечную подпапку» и скопировать в новую версию измененных DLL-файлов в эту пустую «библиотечную подпапку». Когда вы «очищаете и перестраиваете» основное приложение, которое вызывает эти библиотеки DLL, Visual Studio Удалось C ++ удалит старые библиотеки DLL из папки «Release» и скопирует новые библиотеки DLL из «подпапки библиотеки» в папку «Release» приложений. Это хорошо держит вашу DLL в актуальном состоянии.

В Неуправляемый С, «Очистить и восстановить» делает не удалите ваши старые DLL из папки «Release» приложения. И это не Скопируйте новую DLL из вашей «библиотечной подпапки» либо. Поэтому, хотя я думал, что я помещаю свои новые DLL в папку, в которой моя программа могла их найти, они не копировались, как в Managed C ++.

По сути, это означает, что любые новые изменения, которые вы вносите в свою C ++ DLL … если вы только копируете их в «библиотечную подпапку» в своем проекте C, новый улучшенный код не будет скопирован в папку Release, как управляемый С ++ делает. Вы также должны скопировать эти новые DLL в папку Release.

Это также означает, что … если у вас была ваша исходная DLL, скомпилированная и связанная, а затем добавленная Callme() Если вы физически не скопировали эту DLL в папку Release, она никогда не увидит ваш новый код. Он по-прежнему будет смотреть на вашу старую версию и даст вам ошибку, которую вы сейчас видите.

Вот некоторые инструменты, которые могут помочь вам отследить даты версий, которые ваши программы действительно пытаются вызвать. Это позволит вам узнать, захватывает ли ваш компоновщик устаревшую версию вашего кода:

link /dump /exports CPPSource.dll | grep subCreate

link /dump /exports CSource.exe | grep subCreate

Ввод правильных имен файлов для .dll и .exe

Если вы не используете DLL для своей библиотеки C ++, вы можете игнорировать мой ответ на решение для вас. (Или вы можете рассмотреть возможность использования DLL для вашего чистого кода C ++ и вызова / ссылки на него в вашем чистом приложении / проекте на языке C.) Я обнаружил, что сохранение кода C ++ полностью отделенным в DLL от основного проекта кода C — это способ сохранить Вы от многих головных болей. (Особенно, если вы смешиваете неуправляемый код и управляемый код.)

Надеюсь, это поможет 🙂

1

Ваша функция C ++ должна быть помечена как extern "C" чтобы избежать искажения имени и следовать C соглашение о вызовах.
Если вы этого не сделаете, он не будет (легко) вызываться из C.

Вышеприведенное также означает, что вы не можете использовать значения аргументов по умолчанию или перегрузку (и более) для таких функций, которые должны вызываться из C.

И вам, конечно, нужно скомпилировать код C ++ с помощью компилятора C ++.

0

Просто глупая опечатка! Вы объявляете и определяете Callme () и вызываете CallMe ()

0

Вы не можете скомпилировать код C ++ с помощью компилятора C.

-1
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector