我有两个.cpp文件,一个叫做practice.cpp,另一个叫做adder.cpp。它们都在Source Files文件夹中。
拳头代码如下所示:
// adder.cpp
#include "stdafx.h" //include library
int addition(int a, int b) //start function
{
int r = 0; //declare variables
r = a + b; //actual code
return r; //output of function
}
第二个代码:
// Practice.cpp
#include "stdafx.h"
#include "adder.cpp"
#include <iostream>
using namespace std;
int main(void)
{
int number1 = 0;
int number2 = 0;
int number3 = 0;
do
{
printf("\n\nInsert value for first number\n\n");
scanf("%d",&number1);
printf("\nthe value ");
printf("%d ",number1);
printf("has been stored in memory location ");
printf("%d",&number1);
printf("\n\nInsert value for second number\n\n");
scanf("%d",&number2);
printf("\nthe value ");
printf("%d ",number2);
printf("has been stored in memory location ");
printf("%d",&number2);
number3 = addition(number1,number2);
printf("%d",number3);
}
while (1==1);
return 0;
}
但代码无法编译。我收到错误:
1>------ Build started: Project: Practice, Configuration: Debug Win32 ------
1> Practice.cpp
1>c:\users\craig\documents\3rd year work\progamable systems\practice\practice\practice.cpp(25): warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(304) : see declaration of 'scanf'
1>c:\users\craig\documents\3rd year work\progamable systems\practice\practice\practice.cpp(33): warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(304) : see declaration of 'scanf'
1>Practice.obj : error LNK2005: "int __cdecl addition(int,int)" (?addition@@YAHHH@Z) already defined in adder.obj
1>C:\Users\Craig\Documents\3rd year work\Progamable Systems\Practice\Debug\Practice.exe : fatal error LNK1169: one or more multiply defined symbols found
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我一直在寻找网络,但看起来我正确地做到了。我该怎么做才能解决这个问题?谢谢!
答案 0 :(得分:3)
不要包含.cpp文件,这就是编译器告诉您多个定义的原因。您必须创建一个标题.h文件并将其包含在两个.cpp文件中,并输入以下内容:
// adder.h
#ifndef ADDER_H
#define ADDER_H
int addition(int, int);
#endif
预处理器句子将告诉编译器只定义一次方法addition
。它有效,祝你好运:)
答案 1 :(得分:2)
当您#include adder.cpp
时,此文件中的所有代码都会复制到此位置。因此,您最终得到addition
函数的2个定义。
这就是为什么建议不要包含cpp
文件,而是包含包含警卫的头文件。
答案 2 :(得分:0)
删除#include "adder.cpp"
并在main函数前使用前向声明:
int addition(int a, int b);