kinoshirosa 2024-08-31 19:52 采纳率: 33.3%
浏览 20

C++多文件程序中头文件函数声明与函数原型不在同一个文件出现id returned 1 exit status


// coordin.h -- strcture templates and function prototypes

// structure templates
#ifndef COORDIN_H_
#define COORDIN_H_
#include <iostream>
#include <cmath>

struct polar {
    double distance;
    double angle;
};

struct rect {
    double x;
    double y;
};

const double Pi = 3.1415927;

// function prototypes
polar rect2polar(rect xypos);
void show_polar(polar dapos);

#endif
#include <iostream>
#include "coordin.h"

int main()
{
    using namespace std;
    rect r_place;
    polar p_place;

    cout << "Enter the x and y values: ";
    while (cin >> r_place.x >> r_place.y) // stick use of cin
    {
        p_place = rect2polar(r_place);
        show_polar(p_place);
        cout << "Next two numbers (q to quit): ";
    }
    cout << "Byebye.\n";
    return 0;
}

// file2.cpp -- contains functions called in file1.cpp
#include <iostream>
#include <cmath>
#include "coordin.h"

// function declaration

polar rect2polar(rect xypos) {
    polar * p_dapos = new polar;
    p_dapos->distance = sqrt(xypos.x * xypos.x + xypos.y * xypos.y);
    p_dapos->angle = atan2(xypos.y, xypos.x) * 180 / Pi;
    return *p_dapos;
}

void show_polar(polar dapos) {
    std::cout << "The distance away from Original Point: " << dapos.distance << std::endl;
    std::cout << "The angle away from X axis: " << dapos.angle << " degrees" << std::endl;
}


img


我在把函数声明放到coordin.h内的时候程序可以运行,但是放到另外一个cpp文件中就会出现id returns 1 exit的错误,请问是什么原因导致的?如何修改?

  • 写回答

1条回答 默认 最新

  • Unity打怪升级 2024-09-04 08:11
    关注

    当你将函数声明从 coordin.h 移动到另一个 .cpp 文件中时,程序出现 id returns 1 exit 错误,通常是因为编译器在链接阶段找不到函数的实现。这可能是由以下几个原因导致的:

    1. 函数声明和定义不匹配:确保在 .cpp 文件中定义的函数与头文件中的声明完全一致,包括函数名、参数类型和数量、以及返回类型。

    2. 头文件包含问题:如果函数声明是从 coordin.h 移动到了另一个 .cpp 文件,确保这个 .cpp 文件包含了 coordin.h

    3. 编译指令问题:确保编译器在编译时包含了所有相关的 .cpp 文件。如果你使用的是命令行编译,确保所有包含函数实现的 .cpp 文件都在编译命令中。

    4. 链接错误:如果函数定义在一个 .cpp 文件中,而其他文件中需要调用这个函数,确保链接器能够找到并链接这个函数的实现。

    5. 命名空间问题:如果函数定义在一个特定的命名空间中,确保在调用该函数的地方使用了正确的命名空间。

    6. 多重定义:如果函数在多个地方被定义,或者在头文件中被定义(而不是声明),可能会导致链接错误。

    7. 静态函数问题:如果函数被定义为 static,它的作用域将被限制在定义它的文件中,其他文件无法访问。

    为了解决这个问题,你可以尝试以下步骤:

    • 确保所有 .cpp 文件都被正确编译并链接。
    • 检查函数声明和定义是否完全一致。
    • 如果函数定义在 .cpp 文件中,确保在头文件中只声明函数,而不是定义。
    • 检查编译器的输出,看是否有未定义的引用错误(undefined reference)。
    • 确保没有重复定义函数。
    评论

报告相同问题?

问题事件

  • 创建了问题 8月31日