Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

cmake

qt

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.

enter image description here

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

like image 268
Kidsunbo Avatar asked Jun 09 '15 06:06

Kidsunbo


1 Answers

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;
}
like image 68
tomvodi Avatar answered Oct 05 '22 15:10

tomvodi