gpt4 book ai didi

c++ - 如何在另一个函数中使用一个函数?

转载 作者:太空宇宙 更新时间:2023-11-04 16:18:04 24 4
gpt4 key购买 nike

我有两个.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 ==========

我一直在网上寻找,但看起来我做得对。我该怎么做才能解决这个问题?谢谢!

最佳答案

不要包含 .cpp 文件,这就是编译器告诉您多个定义的原因。您必须创建一个 header .h 文件并将其包含在您的两个 .cpp 文件中,并放入以下内容:

// adder.h

#ifndef ADDER_H
#define ADDER_H

int addition(int, int);

#endif

预处理器语句会告诉编译器只定义一次方法addition。成功了,祝你好运:)

关于c++ - 如何在另一个函数中使用一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com