c++ - 函数的多重声明 make 命令 UNIX

标签 c++ unix makefile

<分区>

我有 2 个文件,我想使用 make 命令编译和运行它们。我创建了一个名为“Makefile”的 Makefile。它们已编译但显示错误

all: hello
hello: pgm1.o pgm2.o
        g++ pgm1.o pgm2.o -o hello
pgm1.o: pgm1.cpp
        g++ -c pgm1.cpp
pgm2.o: pgm2.cpp
        g++ -c pgm2.cpp

它们已编译但显示错误

make -f Makefile
g++ pgm1.o pgm2.o -o hello
pgm2.o: In function `print2()':
pgm2.cpp:(.text+0x0): multiple definition of `print2()'
pgm1.o:pgm1.cpp:(.text+0x0): first defined here
collect2: ld returned 1 exit status
make: *** [hello] Error 1

pgm1.cpp

#include <iostream>
#include "pgm2.cpp"
using namespace std;
int main()
{
        cout<<"Thiss is program 1";
        print2();
        return 0;
}

<>pgm2.cpp

#include <iostream>
using namespace std;
void print2()
{
        cout<<"Thiss is program 2";

}

那个错误是什么?我该如何纠正它?

最佳答案

您正在将这两个文件编译成单独的输出文件,但是您的 pgm1.cpp 已经通过行 #include "包含函数 print2() pgm2.cpp"...

可能的解决方案是:

1) 删除包含文件并添加函数声明。

void print2();

2) 正如已经指出的那样,创建一个头文件并使用包含它而不是 .cpp 文件。

关于c++ - 函数的多重声明 make 命令 UNIX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35449573/

相关文章:

c - 两个程序,一个 Makefile 中的命名管道

c++ - 试图创建对象列表,operator = 给我带来了麻烦

c++ - 不同对象的 vector 及其迭代器

linux - 关于多个su的说明

c - 如何编写unix "time"之类的实用程序

linux - 如何使用unix在数据库中登录和执行命令?

c++ - 通过命令行设置 CPPFLAGS

linux - 如何在一段时间内制作具有特定大小的文件?

c++ - 使用常量长度时 char[] 和 new char[] 之间的区别

c++ - 结构数组的未定义 C++ 变量