代码之家  ›  专栏  ›  技术社区  ›  anubhav nidaria

在linux中用自己的头文件编译和运行c++程序

  •  1
  • anubhav nidaria  · 技术社区  · 10 年前

    这是我第一次制作自己的头文件。我正在尝试在Ubuntu上用C++编写一个简单的HelloWorld程序。制作了如下3个文件:

    //hello.h文件

    #ifndef HELLO_H
    #define HELLO_H
    
    //my own code
    
    void hello();
    
    #endif
    

    //hello.cpp文件

    #include <iostream>
    #include "hello.h"
    
    using namespace std;
    
    void hello()
    {
        cout << "This line is printed from header.";
    }
    

    //main.cpp文件

    #include <iostream>
    #include "hello.h"
    
    using namespace std;
    
    int main()
    {
        cout << "in main" << endl << endl;
        hello();
        return 0;
    }
    

    我试过了

    g++ -I /home/Desktop/hello/ -c hello.cpp -o hello.o
    

    编译头文件,此命令起作用。

    然后,一边做

    g++ -o main main.cpp
    

    我最终出现以下错误:

    /tmp/ccb0DwHP.o: In function `main':
    main.cpp:(.text+0x2e): undefined reference to `hello()'
    collect2: error: ld returned 1 exit status
    

    请建议是否需要在终端的任何文件或命令中进行更改?

    非常感谢。

    3 回复  |  直到 4 年前
        1
  •  9
  •   Uyghur Lives Matter    10 年前

    您没有链接到 你好,o 在下面的命令中:

    g++ -o main main.cpp
    

    试试看:

    g++ -o main main.cpp hello.o
    

    或者对于这样的简单程序,只需发出以下命令:

    g++ -o main main.cpp hello.cpp
    

    为了便于使用,请创建makefile,然后运行make:

    make
    

    一个简单的makefile:

    helloprogram: hello.h hello.cpp main.cpp
    
        g++ -o helloprogram main.cpp hello.cpp
    
    clean:
    
        rm helloprogram
    
        2
  •  0
  •   Ningrong Ye    6 年前

    在Path2Hello中输入hello.h;

    g++ -o main -I Path2Hello main.cpp hello.cpp
    

    ps:-I选项指定备用包含目录(用于头文件)。

        3
  •  -2
  •   jainath kumhar    4 年前

    要编译和运行C语言程序,您需要一个C编译器。要在计算机/笔记本电脑中设置C语言编译器,有两种方法:

    下载一个完整的IDE,如Turbo C或Microsoft Visual C++,附带一个C语言编译器。 或者,您可以使用任何文本编辑器编辑程序文件并单独下载C编译器。