【发布时间】: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 */
main.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 文件中,一切正常。我不明白这里有什么问题。
【问题讨论】:
-
在 xcode 中,尝试选择 selectionsort.cpp,打开右侧面板(Cmd + Option + 0),然后选中 Target Membership 复选框。可能是在添加cpp文件的时候没有勾选,导致没有编译。
-
@TrebledJ 解决了,谢谢