0

我正在测试 CLion IDE,并且正在尝试编写一个最小的 C++ 程序。这是我的代码:

在 main.cpp 中:

#include "classings.h"

int main() {
    classings s;
    s.doSomething();
    return 0;
}

在classings.h中:

class classings {
public:
    void doSomething();
};

在classings.cpp中:

#include <string>
#include <iostream>
#include "classings.h"

void classings::doSomething() {
    std::cout << "hei" << std::endl;
}

我不知道为什么这会给我这个错误:

Undefined symbols for architecture x86_64:
  "classings::doSomething()", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我在 OSX 10.10 上。

4

1 回答 1

0

我认为您的源文件classings.hclassings.cpp没有包含在您的CMakeLists.txt.

如果你打开CMakeLists.txt,它应该看起来像这样:

不完整CMakeLists.txt

cmake_minimum_required(VERSION 2.8.4)
project(untitled)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp) # your other source files aren't listed
add_executable(my-program ${SOURCE_FILES})

您可以通过包含新的源文件来解决问题

正确的CMakeLists.txt

cmake_minimum_required(VERSION 2.8.4)
project(untitled)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp classings.hpp classings.cpp) # manually listing all sources
add_executable(my-program ${SOURCE_FILES})

仅供参考,您可以使用file()aux_source_directory()命令在CMakeLists.txt每次添加/删除新源文件时省去编辑的麻烦。这是一个例子:

set(SOURCE_DIRECTORY "src")
file(GLOB_RECURSE SOURCE_FILES "${SOURCE_DIRECTORY}/*.c"   "${SOURCE_DIRECTORY}/*.h"
                               "${SOURCE_DIRECTORY}/*.cc"  "${SOURCE_DIRECTORY}/*.hh"
                               "${SOURCE_DIRECTORY}/*.cpp" "${SOURCE_DIRECTORY}/*.hpp"
                               "${SOURCE_DIRECTORY}/*.cxx" "${SOURCE_DIRECTORY}/*.hxx")
add_executable(my-program ${SOURCE_FILES})

或者

aux_source_directory("src" SOURCE_FILES)
add_executable(my-program ${SOURCE_FILES})
于 2015-02-14T11:53:22.263 回答