c++ - 无法使用 Gradle 在同一源文件中链接 C++ 方法

标签 c++ macos gradle linker

我正在尝试使用 Gradle (5.6.2) 构建一个基本的 C++ 库,但无法弄清楚这里出了什么问题。我开始使用 Gradle init 来创建基本结构......这是我的 build.gradle:

plugins {
    // Apply the cpp-library plugin to add support for building C++ libraries
    id 'cpp-library'

    // Apply the cpp-unit-test plugin to add support for building and running C++ test executables
    id 'cpp-unit-test'
}

// Set the target operating system and architecture for this library
library {
    targetMachines.add(machines.macOS.x86_64)
    dependencies {
        implementation files('/usr/local/lib/libjsoncpp.a') // used by classA
    }
}

tasks.withType(CppCompile).configureEach {
    compilerArgs.add "-std=c++11"
    compilerArgs.add "-w"
}

源代码树如下所示:
src/main/cpp -> classA.cpp classB.cpp classB.hpp hello.cpp
src/main/public -> classA.hpp cppd.h cpplib.h
src/test/cpp -> classATest.cpp hello_test.cpp

hello.cpp、cppd.h、cpplib.h 和 hello_test.cpp 都来自“gradle init”,实际上并未使用。

classA 调用了 classB 中的一些方法。 classB 仅依赖于标准库。

classB 有一个公共(public)方法 classB::method1() 调用两个私有(private)方法 classB::method2() 和 classB::method3()

当我构建时,我收到一个链接器错误,它找不到 classB::method2() 或 classB::method3()。我检查了方法签名,它们都匹配(classB.hpp、classB.cpp 和链接器错误消息中的参数数量和类型相同)。

我已经搜索了 Gradle 文档并在 Google 上搜索了我能想到的所有内容,尝试了 build.gradle 文件的几种变体,并且......我不明白为什么链接器无法在同一个 CPP 文件中找到方法?

在 MacOS 10.14.6 上使用 Clang 11.0 构建以防万一……

也供引用,这里是头文件的相关位:
class classB {
public:
  method1();
private:
  string& method2(const string& s, bool b);
  int method3(uint16_t* b, const string& s);
}

以及来自 cpp 文件的方法:
string& method2(const string& s, bool b) {
 // blah
}

int method3(uint16_t* b, const string& s) {
  // blah
}

最佳答案

哦,我的天啊!只是……没关系。您知道有时发布问题本身就足以使问题变得明显吗?

作为记录,当然缺少的是 CPP 文件中方法名称前面的类标识符(抱歉,不记得这个词,我从 Java 回来)。他们应该是:

string& classB::method2(const string& s, bool b) {
 // blah
}

int classB::method3(uint16_t* b, const string& s) {
  // blah
}

如果没有类标识符,链接器就不会意识到它们是成员函数,也不会建立连接。

关于c++ - 无法使用 Gradle 在同一源文件中链接 C++ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58455390/

相关文章:

c++ - 创建 C++ 共享库时,是否只需要附加库所依赖的 header ?

ruby - mini_magick gem 不适用于我的 ImageMagick 安装

ruby - 如何在 Mac 上将 Ruby 更新到 1.9.x?

gradle - 如何配置Gradle包装器

Android:在模块 jetified-play-services-measurement 和 jetified-play-services-measurement-impl 中发现重复类

java - 将 lombok 与 gradle 和 spring-boot 一起使用

c++ - Arduino 上一次中断的多个触发器

c++ - 自动换行功能

c++ - 如何设置 Win32 richedit 的上/下边距

c++ - 检查所有使用的 OpenGL 扩展