【问题标题】:Defining function with arrays in different files用不同文件中的数组定义函数
【发布时间】:2021-06-09 02:12:37
【问题描述】:

我想在单独的 C++ 文件中定义一个函数。该函数将数组作为参数。

这些是我的文件。

selectionsort.cpp

#include "selectionsort.hpp"

int selectionsort(int a[]){
    
    int length{};
    length = std::size(a);
    
    for(int i{0}; i < length; ++i){
        int smallestIndex{i};
        
        for(int j{i+1}; j < length; ++j){
            if(a[j] < a[smallestIndex]){
                smallestIndex = j;
            };
        };
    std::swap(a[smallestIndex], a[i]);
    };
    return 0;
};

selectionsort.hpp

#ifndef selectionsort_hpp
#define selectionsort_hpp

int selectionsort(int []);

#endif /* selectionsort_hpp */

ma​​in.cpp

#include "io.hpp"
#include "monsters.hpp"
#include "selectionsort.hpp"
#include <iostream>
#include <iterator>

int main(){
    
    int a[]{ -1, -100, 0, 10, 100, -2, 2, 10000, 45, -10000};
    selectionsort(a);
    
    std::cout << a[0] << '\n';
    std::cout << a[1] << '\n';
    
    
    return 0;
};

Xcode 在我运行程序时显示以下错误。

架构 x86_64 的未定义符号: “selectionsort(int*)”,引用自: main.o 中的 _main ld:未找到架构 x86_64 的符号 clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)

未定义符号:selectionsort(int*)

但是,如果我将 selectionsort.cpp 的函数定义放在 main.cpp 文件中,一切正常。我不明白这里有什么问题。

【问题讨论】:

标签: c++ arrays function


【解决方案1】:

您的 .cpp 文件包含不应编译的错误。因此,我怀疑您根本没有在当前设置中构建它。这可以解释为什么目标代码没有链接到您的应用程序中,并且链接器不满意。

如果你做单独编译,即

g++ a.cpp -c
g++ b.cpp -c

现在你有两个目标文件,a.o 和 b.o。要生成二进制文件,您必须将它们链接在一起:

g++ a.o b.o -o myprogram

在您的代码中,您试图传递一个数组:

int selectionsort(int a[]){
    int length{};
    length = std::size(a);
    ...    

而你根本无法做到这一点。当传递给函数时,数组 衰减 为指针,并且您不能在指针上调用 std::size。这不会编译,因为它丢失了有关参数的数组信息(在其数组类型中编码)并且当它只是一个指针时无法确定它的大小。它不知道你的数组在函数内部有多大。您可以使这项工作的唯一方法是更改​​代码并传递数组的大小连同您的数组。这是一个常见的需求,因此有 span 类,其中一个已添加到 c++20,它基本上将指针和大小捆绑在一起,您可以考虑使用其中之一。

如果您修复构建系统以构建所有代码,则修复上面的 c++ 错误(包括更改标头声明以匹配),然后将所有目标代码链接在一起,这可能会解决您遇到的问题看到。

【讨论】:

  • 谢谢 Chris,虽然我的问题是没有按照@TrebledJ 的建议选择目标成员资格复选框,但您关于数组衰减为指针的建议很有帮助。
猜你喜欢
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-05
  • 2016-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多