im new to C++ language.
So I was assigned to split an existing file into three source code: swap.h, swap.cpp and source3.cpp
Existing File:
#include <iostream>
void get_numbers (int&, int&);
void swap_values (int&, int&);
void show_results (int, int);
int main () {
int first_num, second_num;
get_numbers (first_num, second_num);
swap_values (first_num, second_num);
show_results (first_num, second_num);
return 0;
}
void get_numbers (int& input1, int& input2) {
using namespace std;
cout << "Enter two integers: ";
cin >> input1 >> input2;
}
void swap_values (int& variable1, int& variable2) {
int temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
void show_results (int output1, int output2) {
using namespace std;
cout << "In reverse order the numbers are: "
<< output1 << " " << output2 << endl;
}
swap.h contains function prototypes
swap.cpp contains function implementations
source3.cpp contains the main function
for swap.h:
#pragma once
#ifndef swap_h
#define swap_h
void get_numbers(int&, int&);
void swap_values(int&, int&);
void show_results(int, int);
#endif
for swap.cpp
#include <iostream>
void get_numbers(int& input1, int& input2) {
using namespace std;
cout << "Enter two integers: ";
cin >> input1 >> input2;
}
void swap_values(int& variable1, int& variable2) {
int temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
void show_results(int output1, int output2) {
using namespace std;
cout << "In reverse order the numbers are: "
<< output1 << " " << output2 << endl;
}
for source3.cpp:
#include "stdafx.h"
#include "swap.h"
int main()
{
int first_num, second_num;
get_numbers(first_num, second_num);
swap_values(first_num, second_num);
show_results(first_num, second_num);
return 0;
}
When I debug the program, it says: "Unable to start program 'C:\User......'
The system cannot find the file specified. What am I doing wrong?
Since your code compiles successfully, but cannot be started, you probably have problems related to your debugging environment.
Also, you don't need #ifdef, #define, and #endif once you have #pragma once.
If what you provided is the whole code, you didn't include swap.h in swap.cpp. Therefore you have the definition of the functions, but no declaration. Although I would imagine another error or at least a warning here. Try to fix that.
If it doesn't work, try building the Release Version. Does it compile? Does it start? And when it is starting, does it do anything? If what I mentioned before is the problem, I would expect the program to just run to the end, without doing anything.
If the problem lies with swap.h in the main File, make sure it is in the same location, or the include paths point to the directory which contains it. Same goes for stdafx.h
Also, you don't need #pragma once and #ifndef #define and #endif. Get rid of either of those, I recommend using #ifndef #define and #endif, because #pragma once is not supported everywhere. But for you it shouldn't matter.
Related
I have 2 files, main.cpp and xyz.cpp, xyz.cppp have function that making some calculation (and should to output it at the end), and i want call this function from switch in main.cpp
main.cpp :
#include <iostream>
#include <math.h>
#include <cstdlib>
#include "xyz.cpp"
int cl;
using namespace std;
int main(int argc, const char * argv[]){
cout << ("Make ur choice (1-1)");
cin >> cl;
switch(cl){
case (1):{
// I suppose it should be called here somehow
}
}
return 0;
}
xyz.cpp:
using namespace std;
int function() {
cout << "Input number: ";
cin >> a;
o1p1 = (1+cos(4*a));
o1p2 = (1+cos(2*a));
o1 = ((sin(4*a))/o1p1)*((cos(2*a))/o1p2);
cout << "\nZ1 = ";
cout << o1;
cout << "\n ";
return 0;
}
Where you have your comment, simply write:
function();
However, note that typically you will want to include header files (i.e. a file with function declarations), rather than source files (a file with the definitions).
In the header you will have:
int function();
The source file would be the same.
Note that this will mean that you will have to compile both source files, rather than just the main one.
Rename your method, otherwise the call is going to be ambiguous.
Use a header file named "xyz.h", where you declare your method. Then, in the main.cpp file, include that header file (instead of its source file). The source file "xyz.cpp" should include the header file as well. Then in main.cpp, just call the method like this: int returnedValue = myFunction();
Complete example:
xyz.h
#ifndef XYZ_H
#define XYZ_H
int myFunction();
#endif /* XYZ_H */
xyz.cpp
#include <iostream>
#include <cmath>
#include "xyz.h"
using namespace std;
int myFunction() {
float a, o1p1, o1p2, o1;
cout << "Input number: ";
cin >> a;
o1p1 = (1+cos(4*a));
o1p2 = (1+cos(2*a));
o1 = ((sin(4*a))/o1p1)*((cos(2*a))/o1p2);
cout << "\nZ1 = ";
cout << o1;
cout << "\n ";
return 0;
}
main.cpp
#include <iostream>
#include "xyz.h"
using namespace std;
int main(int argc, const char * argv[]) {
int cl;
cout << ("Make ur choice (1-1)");
cin >> cl;
switch(cl){
case (1):{
int returnedValue = myFunction();
cout << returnedValue << endl;
}
}
return 0;
}
Output:
Georgioss-MBP:Desktop gsamaras$ g++ main.cpp xyz.cpp -lm
Georgioss-MBP:Desktop gsamaras$ ./a.out
Make ur choice (1-1)1
Input number: 2
Z1 = -2.18504
0
I am learning about functions and classes, and wrote my own code. I used the constructor to just initialize the variables. I have a function that is supposed to get the info I initialized with the constructor and allow me to display it. However, it doesn't want to work. I am not really sure what I am doing wrong. My error code says that I have unresolved externals because of my "void" function. I thought my function was not returning anything but rather just displaying the input it got from the initialization of the constructor.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
};
void GetBerryInfo (const Berries& B);
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
cout << GetBerryInfo;
system("pause");
return 0;
}
There are several mistakes.
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
should be
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
==================================================================
void GetBerryInfo (const Berries& B);
should be removed.
==================================================================
cout << GetBerryInfo;
should be
Berryinfo1.GetBerryInfo();
==================================================================
All computer langauges are fussy, you have to get the details right, as well as understand the concepts.
This will do what you wanted:
# include <iostream>
# include <iomanip>
# include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
};
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
Berryinfo1.GetBerryInfo();
system("pause");
return 0;
}
A couple of points on your mistakes:
GetBerryInfo() was declared inside the class. You don't need to re-declare it in the global scope. That 2nd declaration should be removed.
To be invoked, functions (like GetBerryInfo) must have () at the end of them like so: GetBerryInfo().
There is no point for GetBerryInfo() to take Berries as a paremeter. It is a member function that is part of the class Berries. It has access to all data members of a Berries instance already.
You don't need to use cout here: cout << GetBerryInfo; because the function body already sends the data members to cout. This function returns void so it doesn't make sense to send this to cout anyway.
I'm learning C++ and tutorial asks me to add another project to what I have now.
Also I'm asked to use forward declaration so I can make use of that added file.
Here is my main project:
#include <iostream>
#include "io.cpp"
using namespace std;
int readNumber();
void writeResult(int x);
int main() {
int x = readNumber();
int y = readNumber();
writeResult(x + y);
return 0;
}
here's the added file called io.cpp:
#include <iostream>
using namespace std;
int readNumber() {
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void writeResult(int x) {
cout << "Sum of your numbers is " << x << endl;
}
![And here's a screenshot so you can see what error I'm getting which talks about multiple definition and you can see where those two files are added.
According to the tutorial my code is okay but compiler complains. Why ?]1
In codeblocks, when creating a new class, it should automatically header file. Programming with header files is the best practice out there. Here's the code I tried and it worked, with io.h.
main.cpp
#include <iostream>
#include "io.h"
using namespace std;
io inOut;
int main()
{
int x = inOut.readNumber();
int y = inOut.readNumber();
inOut.writeResult(x + y);
return 0;
}
io.h
#ifndef IO_H
#define IO_H
class io
{
public:
int readNumber();
void writeResult(int);
};
#endif
io.cpp
#include <iostream>
#include "io.h"
using namespace std;
int io::readNumber()
{
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void io::writeResult(int x)
{
cout << "Sum of your numbers is " << x << endl;
}
I used codeblocks to compile the code written above, and it worked perfectly.
Well as turns out when adding more cpps they're not supposed to be #included on the top. That's what makes compiler say that function is being defined multiple times. All I had to do was just get rid off that one line.
Here's my source:
http://www.cplusplus.com/forum/beginner/44651/
I'm attempting to practice some coding in my free time (combining a number of different interests of mine to help keep myself engaged) and I've encountered a odd error that I can't find the answer to. I have 4 files that I'm working with, two header files, one class definition file and a main file. I'm fairly confident I'm not including the Dice.h file more then once (however that is where the error points to and I'm not sure anymore, hence this question). What have I bungled here to produce these errors?
The error codes
Error 3 error LNK1169: one or more multiply defined symbols found (file path trimmed)
Error 2 error LNK2005: "int __cdecl dice(int,int)" (?dice##YAHHH#Z) already defined in Creature.obj (file path trimmed)
The filepath: c:\Users\Username\documents\visual studio2010\Projects\RPGTest\RPGTest\RPGTest.(error 3 referenced a .exe file, error 2 referenced a .obj file).
The code itself:
Dice.h
#ifndef SET_DICE_H_
#define SET_DICE_H_
#include <iomanip>
#include <iostream>
#include <stdlib.h>
using namespace std;
int dice(int number, int sides){
int total=0, dice;
srand(time(NULL));
int results=0;
do {
dice = rand()%sides+1;
total+=dice;
number--;
} while (number > 0);
results = total;
return results;
}
#endif
Creature.h
#ifndef CREATURE_H_
#define CREATURE_H_
#include <iomanip>
#include <iostream>
#include "Dice.h"
using namespace std;
class Creature {
public:
Creature(int,int,int,int,int,int,int,int,int,int,int,int);
void set_hp();
void set_saves();
void set_ac();
void set_bab();
void set_name();
void update_hp(int);
void update_ac(int);
void update_fsave(int);
void update_rsave(int);
void update_wsave(int);
int get_ac();
int get_hp();
int get_fsave();
int get_rsave();
int get_wsave();
int get_bonus(int);
int get_bab();
string get_name();
private:
int strength, dexterity, constitution, intellegence, wisdom, charisma;
int bab, fbsave, rbsave, wbsave;
int hdnum, hdsize;
int hp, fsave, rsave, wsave, ac;
string name;
};
#endif
Creature.cpp
#include "Creature.h"
#include <math.h>
#include <iostream>
using namespace std;
Creature::Creature(int strength,int dexterity,int constitution,
int intellegence,int wisdom,int charisma,int bab,int fbsave,
int rbsave,int wbsave,int hdnum,int hdsize){
strength = strength;
dexterity = dexterity;
constitution = constitution;
intellegence = intellegence;
wisdom = wisdom;
charisma = charisma;
bab = bab;
fbsave = fbsave;
rbsave = rbsave;
wbsave = wbsave;
hdnum = hdnum;
hdsize = hdsize;
}
int Creature::get_bonus(int stat){
int bonus = floor((double(stat)-10)/2);
return bonus;
}
void Creature::set_ac(){
ac=10+get_bonus(dexterity);
}
void Creature::set_hp(){
hp = dice(hdnum,hdsize) + get_bonus(constitution)*hdnum;
}
void Creature::set_saves(){
fsave = fbsave + get_bonus(constitution);
rsave = rbsave + get_bonus(dexterity);
wsave = wbsave + get_bonus(wisdom);
}
void Creature::set_bab(){
bab = hdnum;
}
void Creature::set_name(){
cout << "Please enter a name for this creature: ";
cout << "\nSorry! I don't work yet!";
cout << "\nInstead all creatures are named Larry!\n";
name = "Larry!";
}
void Creature::update_hp(int input){
hp = hp + input;
}
void Creature::update_fsave(int input){
fsave = fsave+input;
}
void Creature::update_rsave(int input){
rsave = rsave+input;
}
void Creature::update_wsave(int input){
wsave = wsave+input;
}
void Creature::update_ac(int input){
ac = ac+input;
}
int Creature::get_ac(){
return ac;
}
int Creature::get_hp(){
return hp;
}
int Creature::get_fsave(){
return fsave;
}
int Creature::get_rsave(){
return rsave;
}
int Creature::get_wsave(){
return wsave;
}
int Creature::get_bab(){
return bab;
}
RPGTest.cpp
#include "Creature.h"
#include <math.h>
//#include "Dice.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int str = dice(3,6), dex = dice(3,6), con = dice(3,6), intel = dice(3,6), wis = dice(3,6), cha = dice(3,6);
int fbs = dice(1,6), rbs = dice(1,6), wbs = dice(1,6);
int hdn = dice(1,10), hds = 8, bab = dice(1,8);
cout << "Welcome to RPG Creature Tester v0.1\n";
cout << "This .exe file is meant to test the creature class functions and definitions.\n";
cout << "This will be done by randomly generating and displaying a creature.\n";
cout << "What you don't see right now is the random generation of a creature.\n";
cout << "Once it's finished, the \'statsheet\' will be shown.\n";
cout << "Cheers!\n\n";
Creature potato (str, dex, con, intel, wis, cha, bab, fbs, rbs, wbs, hdn, hds);
potato.set_ac();
potato.set_hp();
potato.set_name();
potato.set_saves();
cout << "OUTPUT BRICK YAY\n";
cout << "Str: " << str << endl;
cout << "HP: " << potato.get_hp() << " AC: " << potato.get_ac() << " Fort/Reflex/Will Save: " << potato.get_fsave() << "/" << potato.get_rsave() << "/" << potato.get_wsave();
return 0;
}
Since I'm mainly self-taught I'm happy for any other advice but my main issue is that I'm not sure why I'm getting the "multiple" definition error. I did some research into other questions with similar error messages but I didn't see anything that immediately jumped out at me as "the answer".
Thanks all!
C++ works by compiling single translation units and then linking them together.
This means that each source file gets compiled on its own. Since the #include directive basically inserts all the code included, in your situation you end up having multiple translation units which define
int dice(int number, int sides) {
...
}
Compilation goes through fine but, when linking, multiple definition of this function are found so this generates the error.
To solve this problem you have two ways:
declare int dice(int, int) in a header file but define (implement it) in a source file
keep the definition as it is but prepend static to it. This tells the compiler that each translation unit will get its own dice method. This solution, although tempting, leads to binary size increase since you will have multiple implementation of the same method
I'm new to CPP, and I want to know how to run a function that isn't in its scope. I'm used to doing such things in javascript, and I get an error CPP when I try to do that. What I mean is the below:
#include <iostream>
using namespace std;
int tic_h;
int tic_v;
void echo(string e_val){
cout << e_val;
}
void c_mes(){
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
s_v();
}
void s_v(){
echo("Please enter vertical coordinate: ");
cin >> tic_v;
if(tic_v<4&&tic_v>0){
c_mes();
}else{
s_v();
}
}
void s_h(){
echo("Please enter horizontal coordinate: ");
cin >> tic_h;
if(tic_h<4&&tic_h>0){
s_v();
}else{
s_h();
}
}
int main(){
s_h();
return 0;
}
I get this error:
error: 'sv' was not declared in this scope on line 16
How can I make it work?
You should put a function prototype before using the function, for the compiler to know what it is going to be.
Put
void s_v(); // prototype your functions, this is usually done in include files
Right after the #include line.
You'll need to forward declare dostuff, as in the example below.
By doing this you pretty much tell the compiler that the function will be defined else where, but that you'd like to use it.
Excuse the wording, but putting it the way I did is easily comprehensive by a novice programmer.
#include <iostream>
using namespace std;
void dostuff (); // forward declaration
void test(int b){
if(b<11&&b>0){
cout << "Yay!";
}
else{
cout << "The number is not between 1 and 10.";
dostuff();
}
}
void dostuff(){
int numput;
cout << "Please type a number between 1 and 10:";
cin >> numput;
test(numput);
}
int main(){
dostuff();
}
OP just edited the original snippet provided in his question (which the below is a modification off), I'll leave this post the way it is since it explains the situation quite well.
You need to add void s_v(); before the c_mes() function. This is called a function prototype, and it lets the compiler know that that symbol exists and will be implemented later in the code:
#include <iostream>
using namespace std;
int tic_h;
int tic_v;
void s_v();
void echo(string e_val) {
cout << e_val;
}
void c_mes() {
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
s_v();
}
void s_v() {
echo("Please enter vertical coordinate: ");
cin >> tic_v;
if (tic_v < 4 && tic_v > 0) {
c_mes();
} else {
s_v();
}
}
void s_h() {
echo("Please enter horizontal coordinate: ");
cin >> tic_h;
if (tic_h < 4 && tic_h > 0) {
s_v();
} else {
s_h();
}
}
int main() {
s_h();
return 0;
}
Keep in mind that if you ever change the signature for s_v() (that is, add arguments or change the return type), you will need to update the prototype as well.
Declare dostuff somewhere before the void test definitionm e.g on line 3:
void dostuff();
This way you introduce the signature of dostuff function to your program before the function is defined.
In C++ unlike javascript and some other languages, the parser doesn't find all functions then compile the code.
add
void dostuff();
just after the using namespace std; and it will work :)
This is the same error, you use a function before declare it (s_v()), for solve your error you only should create a prototype of s_v():
void s_v(); //at the start of your file
write this
void c_mes(){
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
echo("-----\n");
echo("X|0|X\n");
s_v();
}
after this
void s_h(){
echo("Please enter horizontal coordinate: ");
cin >> tic_h;
if(tic_h<4&&tic_h>0){
s_v();
}else{
s_h();
}
}