0

My C++ function example.cpp

#include <sapi.h>
#include <sphelper.h>
#include <atlcomcli.h>
#include <stdio.h>

int texttospeech()
{
    HRESULT                 hr = S_OK;
    CComPtr <ISpVoice>      cpVoice;
    CComPtr <ISpStream>     cpStream;
    CSpStreamFormat         cAudioFmt;

    if (FAILED(::CoInitialize(NULL)))
        return 0;
    //Create a SAPI Voice
    hr = cpVoice.CoCreateInstance( CLSID_SpVoice );
    printf("%d",hr);
    //Set the audio format
    if(SUCCEEDED(hr))
    {
        hr = cAudioFmt.AssignFormat(SPSF_22kHz16BitMono);
        printf("set audio format");
    }
    printf("%d",hr);

    //Call SPBindToFile, a SAPI helper method,  to bind the audio stream to the file
    if(SUCCEEDED(hr))
    {
        hr = SPBindToFile( L"d:\\test.mp3",  SPFM_CREATE_ALWAYS,
            &cpStream, & cAudioFmt.FormatId(),cAudioFmt.WaveFormatExPtr() );

        printf("set audio format");
    }
    printf("%d",hr);
    //set the output to cpStream so that the output audio data will be stored in cpStream
    if(SUCCEEDED(hr))
    {
        hr = cpVoice->SetOutput( cpStream, TRUE );
    }
    printf("%d",hr);    
    //Speak the text "hello world" synchronously
    if(SUCCEEDED(hr))
    {
        hr = cpVoice->Speak( L"Hello!! How are you?",  SPF_DEFAULT, NULL );
    }
    printf("%d",hr);
    //close the stream
    if(SUCCEEDED(hr))
    {
        hr = cpStream->Close();
    }
    printf("%d",hr);

    //Release the stream and voice object
    cpStream.Release ();
    cpVoice.Release();

    ::CoUninitialize();
    return 0;
}

My C code like example1.c

#include <stdio.h>
#include "example.h"

int main(void) {
    texttospeech();
}

Created a header as example.h

#ifdef__cplusplus
    extern "C" {
#endif
int texttospeech();
#ifdef__cplusplus
    }
#endif

Getting:

unresolved external symbol _texttospeech referenced in function _main

Not sure how to use call C++ func in C, I am a beginner trying to integrate C and C++. What other ways can I do this? Is there a way by creating a shared library?

Ahmad Khan
  • 2,655
  • 19
  • 25
  • Note in particular, that your function **in the .cpp file** must be marked `extern "C"` as well. If not, you are defining a different (C++ instead of C) function than the one which is declared in the header. – EmDroid Oct 02 '16 at 12:03
  • The compiler must see the `extern "C"` declaration in example.cpp too. You must `#include "example.h"` in example.cpp as well. – Olaf Dietsche Oct 02 '16 at 12:11

0 Answers0