Include and run function from other file - c++

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

Related

How to execute a function in external file the name of which is stored in a string and also print the content of the file?

Goal: If I want to cout the source code of a function in an external '.cpp' before using it...
Question: How do I do that if the name of the function is stored in a string?
I'm trying to cout the contents of the file and then ask the user if he's sure he wants to execute it...
If the user chooses to execute the function, only then it'll be executed after system(cls).
Here's the outline of the code:
#include<iostream>
#include <string> /* Included all string related headers to play safe */
#include <cstring> /* (I have no idea what these do...) ;P */
#include <fstream>
#include <sstream>
#include "foo1.cpp"
#include "foo2.cpp"
#include "foo3.cpp"
using namespace std;
int exeFunc(string func){
system("cls");
func; //call the function 'foo2()' from 'foo2.cpp'
}
int printFile(string prog){
char ch;
ifstream fin;
fin.open( prog.c_str() ); //this.cpp is the name of the current file
while( !fin.eof() )
{
fin.read( (char*)&ch, sizeof(ch) );
cout << ch;
}
return 0;
}
int selectProg(){
int op;
cout<<"Which Prog would you like to view?\nOptions:\n1\t2\t3 >> ";
cin>>op;
return op;
}
int main(){
int p, a, e;
p = selectProg();
stringstream ss1;
ss1 << "foo" << p << ".cpp";
string prog = ss1.str();
stringstream ss2;
ss2 << "foo" << p << "();";
string func = ss2.str();
a = printFile(prog);
e = exeFunc(func);
return 0;
}
Content of all the foo$.cpp files, is of the form:
#include<iostream>
using namespace std;
foo1(){
cout<<"Hello!! This is foo1 function!"<<endl;
}
I know my current code won't work as, the function exeFunc() isn't right.
int exeFunc(string func){
func; //call the function 'foo2()' from 'foo2.cpp'
}
How can I achieve this?? Any help/insight/alternate approach is appreciated...
Thanks...

clang: error: linker command failed with exit code 1 (use -v to see invocation) console app

this code should work but I am getting a linker error. I don't know where to look to fix this. I keep seeing things about cocoa pods and I don't have cocoa pods.
//main.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "ItemToPurchase.cpp"
#include "ItemToPurchase.hpp"
int main(int argc, const char * argv[]) {
// insert code here...
// create objects
ItemToPurchase item1;
//ItemToPurchase item2;
std::cout << "Item1" << std::endl;
item1.setName();
//item1.SetPrice();
//item1.SetQuantity();
std::cout << "Item2" << std::endl;
//item2.setName();
//item2.SetPrice();
//item2.SetQuantity();
//test
std::cout << std::endl << std::endl;
//item1.getName();
//item1.GetPrice();
//item1.GetQuantity();
return 0;
}
here is the ItemToPurchase class cpp file
//ItemToPurchase
#include "ItemToPurchase.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
std::string ItemToPurchase::setName(){
std::cout << "Enter the item name: " << std::endl;
std::cin >> ItemToPurchase::ItemName;
return ItemToPurchase::ItemName;
}
/*
std::string ItemToPurchase::getName() {
return ItemToPurchase::ItemName;
}
int ItemToPurchase::SetPrice(){
std::cout << "Enter the item price: " << std::endl;
std::cin >> ItemToPurchase::ItemPrice;
return ItemToPurchase::ItemPrice;
}
int ItemToPurchase::GetPrice(){
return ItemToPurchase::ItemPrice;
}
int ItemToPurchase::SetQuantity() {
std::cout << "Enter the Quantity: " << std::endl;
std::cin >> ItemToPurchase::ItemQuantity;
return 0;
}
int ItemToPurchase::GetQuantity() {
return ItemToPurchase::ItemQuantity;
}
*/
and here is the header file for that cpp file it just has the class declaration.
#ifndef ItemToPurchase_hpp
#define ItemToPurchase_hpp
#include <stdio.h>
#include <stdlib.h>
#include <string>
class ItemToPurchase {
public:
std::string setName();
std::string getName();
int SetPrice();
//int GetPrice();
//int GetQuantity();
//int SetQuantity();
//ItemToPurchase();
private:
std::string ItemName = "none";
int ItemPrice = 0;
int ItemQuantity = 0;
} items;
#endif /* ItemToPurchase_hpp */
and this is the full error
duplicate symbol __ZN14ItemToPurchase7setNameEv in:
/Users/devintripp/Library/Developer/Xcode/DerivedData/zybooksLab4-alhksylvtcikaegvkzyxidlzoyib/Build/Intermediates.noindex/zybooksLab4.build/Debug/zybooksLab4.build/Objects-normal/x86_64/ItemToPurchase.o
/Users/devintripp/Library/Developer/Xcode/DerivedData/zybooksLab4-alhksylvtcikaegvkzyxidlzoyib/Build/Intermediates.noindex/zybooksLab4.build/Debug/zybooksLab4.build/Objects-normal/x86_64/main.o
duplicate symbol _items in:
/Users/devintripp/Library/Developer/Xcode/DerivedData/zybooksLab4-alhksylvtcikaegvkzyxidlzoyib/Build/Intermediates.noindex/zybooksLab4.build/Debug/zybooksLab4.build/Objects-normal/x86_64/ItemToPurchase.o
/Users/devintripp/Library/Developer/Xcode/DerivedData/zybooksLab4-alhksylvtcikaegvkzyxidlzoyib/Build/Intermediates.noindex/zybooksLab4.build/Debug/zybooksLab4.build/Objects-normal/x86_64/main.o
ld: 2 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
If main.cpp and ItemToPurchase.cpp are compiled apart, then definition of setName method is duplicated, because first definition is in main.cpp (line #include "ItemToPurchase.cpp" included content of source file where definition of setName is) and the second definition is in ItemToPurchase.cpp . So to resolve this you should remove #include "ItemToPurchase.cpp" from main.cpp file.
Second problem, you cannot define variables in header file, look at definition of ItemToPurchase class
class ItemToPurchase {
public:
//...
} items; // you have defined items variables in header
you should delete items.

Separating a class into cpp and header file (C++)

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.

Compiling two projects together in Code Blocks

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/

Use a function in different file and different namespace in Visual C++

I am struggling with my first steps in C++. Already asked this question, but did not get the full answer specifically about namespace.
I did the following.
In Visual Studio 2015 created am empty project(New Project -> Visual C++ -> Empty Project)
Then I added two files in Source.cpp and PrintFunc.cpp whose respective contents are as follows.
Source.cpp
#include <iostream>
using namespace std;
int PrintHello();
extern int tempCount;
void main()
{
int i;
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
PrintFunc.cpp
#include <iostream>
using namespace std;
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
This is compiling perfectly.
Now I am learning about namespaces, so I just tried to put the contents of the second file in a namespace as follows.
PrintFunc.cpp (modified)
#include <iostream>
using namespace std;
namespace MyNameSpace
{
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
}
And now I modified the Source.cpp also to reflect the namespaces introduction in the previous snippets.
#include <iostream>
using namespace std;
int MyNameSpace::PrintHello();
extern int MyNameSpace::tempCount;
void main()
{
int i;
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
This simply does not compile. Can someone please kindly correct me. My objective is to understand namespace concept in c++. Also I have good exp with C#.
The problem that compiler does not know about namespace MYSpace when compiling Source.cpp.
#include <iostream>
using namespace std;
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
int main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
But this sample is useless. It work only because you have only one consumer .cpp.
You should use .h file and then include it (PrintFunc.h) in Source.cpp and any other .cpp when you want to use that funtions.
I'll write an example:
Print.h
#pragma once
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
Notice that we dont't use additional includes and using namespace here. We would use includes only to use some classes in functions interfaces.
using namespace could "spoil" consumer's .cpp or .h.
Print.cpp
#include <iostream>
#include "Print.h"
using namespace std;
int MyNameSpace::tempCount = 111;
int MyNameSpace::PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
Here we can set any include it will not touch any other files.
And consumer .cpp:
#include <iostream>
#include "Print.h"
using namespace std;
int main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
VS specific: #pragma once and for VS you have to #include "stdafx.h" at first line in any .cpp
You have to supply namespace name when using its members. Or use using namespace directive.
void main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
However, for it to work namespace should be declared in the separate .h file and it should be included in your source.cpp
So finally here it is that I have settled for based on Dmitriy Zapevalov answer.
First Print.h
#pragma once
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
Next PrintFunc.cpp
#include <iostream>
#include "Print.h"
using namespace std;
namespace MyNameSpace
{
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
}
PrintFunc.cpp can also be like this as an alternative.
PrintFunc.cpp (alternative)
#include <iostream>
#include "Print.h"
using namespace std;
int MyNameSpace::tempCount = 111;
int MyNameSpace::PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
And finally Source.cpp
#include <iostream>
#include "Print.h"
using namespace std;
using namespace MyNameSpace;
void main()
{
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
Source.cpp can also be like this as an alternative.
Source.cpp (alternative)
#include <iostream>
#include "Print.h"
using namespace std;
void main()
{
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}