简体   繁体   中英

How to add a class in Qt Creator with CMake project?

I used to write code with Visual Studio, which is pretty easy to add a class. Recently, I turn to use Qt Creator to write pure C++ project and there are always something wrong with adding a class. The codes are like these:

#include <iostream>
#include "hello.h"

using namespace std;

int main()
{
    Hello H;
    H.say();
    cout << "Hello World!" << endl;
    return 0;
}

I created a class named Hello and include it into the main.cpp, but when I compile it, some errors will happen.

在此输入图像描述

So how to add a class with QT creator? Thanks in advance!

A really small CMake example project that uses a main.cpp and a Hello class would look like this:

CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.11)

project(example)

# Useful CMake options for Qt projects
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)

# Search desired Qt packages
find_package(Qt5Core REQUIRED)

# Create a list with all .cpp source files
set( project_sources
   main.cpp
   hello.cpp
)

# Create executable with all necessary source files
add_executable(${PROJECT_NAME}
  ${project_sources}
)

qt5_use_modules( ${PROJECT_NAME} Core )

main.cpp:

#include <iostream>
#include "hello.h"

using namespace std;

int main()
{
    Hello H;
    H.say();
    cout << "Hello World!" << endl;
    return 0;
}

Hello.h:

#ifndef HELLO_H
#define HELLO_H


class Hello
{
public:
   Hello();
   void say();
};

#endif // HELLO_H

Hello.cpp:

#include <iostream>
#include "Hello.h"

Hello::Hello()
{

}

void Hello::say()
{
   std::cout << "Hello from hello class!" << std::endl;
}

Manual way : Edit the .pro, then add the .h and the .cpp in the "SOURCES" and "HEADERS" section like this:

SOURCES += hello.cpp
HEADERS += hello.h

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM