【问题标题】:(.text+0x20): undefined reference to `main' When trying to Compile .cpp file(.text+0x20): 尝试编译 .cpp 文件时未定义对“main”的引用
【发布时间】:2014-06-07 04:55:42
【问题描述】:

当尝试使用位于不同文件夹中的名为 normalize 的 .h 文件(rat.h 与 rat.cpp 位于同一文件夹中)编译名为 rat 的 .cpp 文件时,我正在输入

g++ -I/opt/cis/include/ -I/opt/cis/lib/ rat.cpp

我在 .cpp 文件本身中包含了一个 int main() ,并完全注释掉了 .h 文件和 .cpp 文件的内部工作,只是为了尝试正确编译。

.h 文件(不包括注释项)

  1 #ifndef RAT_H
  2 #define RAT_H
  3 #include <iostream>
  4 #include <string>
  5 
  6 class Rat {
  7         friend std::ostream &operator<<(std::ostream &, const Rat &);
  8         friend std::istream &operator>>(std::istream &, Rat &);
  9         private:
 10                 double n,d;
 11         public: 
 12                 Rat(): n(0), d(1) {}
 13 };
 14. #endif

.cpp 文件

  1 #include <iostream>
  2 #include <cstdlib>
  3 #include <string>
  4 #include <sstream>
  5 #include "rat.h"
  6 #include "normalize.h"
  7 using namespace std;
  8 #ifdef TEST_RAT
  9 int main() {};
  10 #endif

我做错了什么?对不起,如果很明显。

【问题讨论】:

    标签: c++


    【解决方案1】:

    您的main 函数只有在定义了宏TEST_RAT 时才存在。要么:

    • -DTEST_RAT 添加到您的编译器CFLAGS
    • #ifdef 之前添加行#define TEST_RAT 之前
    • 删除 .cpp 中的 #ifdef TEST_RAT#endif

    【讨论】:

    • main有两个允许的签名:int main()int main(int argc, char **argv)
    • 允许,但不是标准。
    • 我不完全确定,但我认为它也是标准的。带有-Wall -Wextra -pedantic 的 GCC 不要抱怨。
    • 对不起,你是对的。不符合标准的是void main
    【解决方案2】:

    你忘了:

    #define TEST_RAT
    

    这没有在您的代码中定义,所以现在应该可以工作了。

    【讨论】:

      【解决方案3】:

      由于您将main() 放在#ifdef 中,因此如果未定义TEST_RAT,则会将其排除在外。因为它不是你没有main,所以你不能创建一个可执行文件(没有入口点)并且g++ 失败并出现错误。

      【讨论】:

        【解决方案4】:

        您很可能希望将其放在 main 中(以确保定义了 Rat 类):

            #ifdef RAT_H
            int main() {};
            #endif
        

        【讨论】:

          【解决方案5】:

          另一个选项,因为还没有人提到它,是-c 标志:

          g++ -c -I/opt/cis/include/ -I/opt/cis/lib/ rat.cpp
          

          这会将 rat.cpp 编译为目标文件 rat.o 而不会尝试将其链接到程序中(因此需要 main)。

          如果您正在测试正确性,您可能还想尝试-W-Wall 以获取警告。

          【讨论】:

          • -c 编译文件并将其输出到目标文件。如果你只想测试它是否编译,你也可以添加-o /dev/null选项
          猜你喜欢
          • 2020-03-25
          • 2013-12-29
          • 1970-01-01
          • 2017-11-29
          • 2012-08-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多