Important: Please read the Qt Code of Conduct -

How to use c++ library in .c file

  • There is a Test.c File in my project.
    Contents of Test.c:

    #include <iostream>

    Using Qt Creator to compile it, I will get the following errors:


    I do think it's compilers error but I don't know how to solve it, because Any Qt Headers will need c++ compiler.

    When inputing #include <QDebug>, following errors occured:


    I want to treat .c file as c++ file, erros could not be eliminated unless I change the suffix .c to .cpp.

  • @brifuture
    Is your question that the code you show should be legal for a C program (it is not), or is it that you want to stick with the extension being .c but have the compiler compile it as C++ (like it would for .cpp)? If it's the latter, then you don't say anything about the compiler you are using, you will (presumably) need to specify an option on its command-line somewhere if the compiler supports that.


    It is easier to make a C++ project and use c func calls as extern by changing .c to .cpp

  • Lifetime Qt Champion

    to force .c to compile as c++ you can use the -x option
    (if using gcc)

    -x language
    Specify explicitly the language for the following input files (rather than letting the compiler choose a default based on the file name suffix). This option applies to all following input files until the next -x option. Possible values for language are:
    c  c-header  cpp-output
    c++  c++-header  c++-cpp-output
    objective-c  objective-c-header  objective-c-cpp-output
    objective-c++ objective-c++-header objective-c++-cpp-output
    assembler  assembler-with-cpp
    f77  f77-cpp-input f95  f95-cpp-input

  • @JoeCFD
    Thank you.
    But that would be much helper if the file suffix coule stay unchanged.
    I believe a .sh or .bat script could do that for me. But it still seems a little troublesome.

  • @JonB
    Thank you,
    To be an honest, I do not care what compiler the file should be processed with.

    I just want to share some codes as a common part between my qt project and mplab project. (Some mathmatical part code, so it would be nice if the codes could be debugged on pc and then put into the MCU).

    While x16 compiler is used as the compiler in the mplab project , so I have to change the behaviour of the shared code with qt project, So any changes I do in qt could be applied into mplab project, and the same inversely.

  • @mrjj
    Thank you.
    I'm using cl.exe (msvc 2015), so the option -x seems effectless.
    I will google some cl options to achieve that.

  • @mrjj
    Wow, that's working! With the following statements in my .pro file
    msvc: QMAKE_CFLAGS += /TP
    the troublesome problem is solved.

  • @BriFuture said in How to use c++ library in .c file:

    the troublesome problem is solved.

    So please mark your post as such! Thanks.

Log in to reply