Mixing C and C++/Qt code



  • @
    #ifdef SUM_H //this is sum.h
    extern "C"{
    #endif

    int mySum(int a,int b);

    #ifdef SUM_H
    }

    #endif // SUM_H
    @


    @
    #include "sum.h" //this is sum.c

    int mySum(int a, int b)
    {

    return a + b;
    

    }
    @


    @
    #include <QtCore/QCoreApplication> // this is main.cpp
    #include <QDebug>
    #include "sum.h"

    int main(int argc, char *argv[])
    {

    QCoreApplication a(argc, argv);
    int i = 5;
    int j = 6;
    int k;
    
    k = mySum(i,j);
    qDebug() << "this sum is " << k;
    return a.exec&#40;&#41;;
    

    }
    @


    but it was wrong with /home/lovebingheji/qt/test-build-desktop-Qt_4_6_2_in_PATH__System__Release/../test/main.cpp:13: error: undefined reference to `mySum(int, int)'

    but when i was iadd #include "sum.c" in main.cpp that is right

    @
    #include <QtCore/QCoreApplication>
    #include <QDebug>
    #include "sum.h"
    #include "sum.c"
    int main(int argc, char *argv[])
    {

    QCoreApplication a(argc, argv);
    int i = 5;
    int j = 6;
    int k;
    
    k = mySum(i,j);
    qDebug() << "this sum is " << k;
    return a.exec(&#41;;
    

    }
    @


    why i just want main.cpp include "sum.h" but "sum.c" how can i should do ?
    i create a QT console application project,please help me.thanks very much



  • my email :lovebingheji@gmail.com please also can answer the question to send my email.



  • Welcome to the forums. Some housekeeping first:

    • wrap code in @-tags or use the editor's button. It makes your code look nicely and adds some pretty printing. I've added them for your, but please format yourself next time
    • adding your question to quite old threads (the "original thread":http://qt-project.org/forums/viewthread/10975/ dates back to October last year) isn't that useful, better open a new thread with a decent topic. I've split your question off to a new thread for that reason.
    • begging for private answers usually leads you to no answers at all. This is a public forum, with everyone answering in their spare times. We do not do private support. Read http://www.catb.org/~esr/faqs/smart-questions.html for some explanations

    Regarding your actual question: The sum.h header file is plain wrong. Use this one

    @
    #ifndef SUM_H
    #define SUM_H

    #ifdef __cplusplus
    extern "C" {
    #endif

    int mySum(int a, int b);

    #ifdef __cplusplus
    }
    #endif
    #endif // SUM_H
    @

    And then make sure that your sum.c implementation file is actually added to the list of source files and gets compiled and linked to your application.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.