error: expected unqualified-id on extern "C"
Asked Answered
A

1

6

I have a cpp code in which I want to call a c function. Both compile well to .o files, but when the clang++ is executing for compilation, I receive the following error:

file.cpp:74:12: error: expected unqualified-id
    extern "C"
           ^

The code in the cpp file is the following:

void parseExtern(QString str)
{
#ifdef __cplusplus
    extern "C"
    {
#endif
        function_in_C(str);
#ifdef __cplusplus
    }
#endif

}

How can I avoid the error ? I can't compile the c file with clang++, I really need to use extern. Thanks.

Architectonics answered 25/5, 2015 at 14:14 Comment(4)
@Mat: That's an answer!! Yes it's a short one but, well, it's an easy question :PTippets
So what's the best way for me to call my C function from CPP ? Regarding QString, I can easily convert to char *.Architectonics
@LaurentCrivello: Declare the function with extern "C". Call it just like any other function.Borrego
@LaurentCrivello - I think This answer addresses your comment question.Schaefer
B
12

The extern "C" linkage specification is something you attach to a function declaration. You don't put it at the call site.

In your case, you'd put the following in a header file:

#ifdef __cplusplus
    extern "C"
    {
#endif
        void function_in_C(char const *); /* insert correct prototype */
        /* add other C function prototypes here if needed */
#ifdef __cplusplus
    }
#endif

Then in your C++ code, you just call it like any other function. No extra decoration required.

char const * data = ...;
function_in_C(data);
Briny answered 25/5, 2015 at 14:26 Comment(1)
This error can also happen if you accidentally put the extern "C" declaration inside a class declaration. Solution: move it outside the class.Placoid

© 2022 - 2024 — McMap. All rights reserved.