如何使用CMake项目在Qt Creator中添加一个类?

Kid*_*nbo 3 c++ qt cmake

我曾经用Visual Studio编写代码,这很容易添加一个类.最近,我转而使用Qt Creator编写纯C++项目,添加类总是有问题.代码如下:

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

using namespace std;

int main()
{
    Hello H;
    H.say();
    cout << "Hello World!" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个名为Hello的类并将其包含在main.cpp中,但是当我编译它时,会发生一些错误.

在此输入图像描述

那么如何使用QT创建者添加一个类?提前致谢!

tom*_*odi 8

使用a main.cppHello类的一个非常小的CMake示例项目看起来像这样:

的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 )
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

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

using namespace std;

int main()
{
    Hello H;
    H.say();
    cout << "Hello World!" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Hello.h:

#ifndef HELLO_H
#define HELLO_H


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

#endif // HELLO_H
Run Code Online (Sandbox Code Playgroud)

HELLO.CPP:

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

Hello::Hello()
{

}

void Hello::say()
{
   std::cout << "Hello from hello class!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)


gal*_*tte 0

手动方式:编辑.pro,然后在“SOURCES”和“HEADERS”部分添加.h和.cpp,如下所示:

SOURCES += hello.cpp
HEADERS += hello.h
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的反对...由于问题没有提到 CMake,答案是完全有效的... (3认同)
  • 抱歉,我不知道您在第一篇文章中使用了 CMake。这是 QMake 解决方案 (2认同)