函数的多个声明使命令 UNIX

Multiple declaration of a function make command UNIX

本文关键字:使命 命令 UNIX 声明 函数      更新时间:2023-10-16

我有 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已经包含函数 print2() 凭借行#include "pgm2.cpp"...

可能的解决方案可以是:

1( 删除包含文件,改为添加函数声明。

void print2();

2(如前所述,创建一个头文件并使用包含它而不是.cpp文件。