Is it possible to call routines from an external file like notepad (or also cpp file if needed)?
e.g.
I have 3 files.
MainCode.cpp
SubCode_A.cpp <- not included in the headers of the MainCode.cpp
SubCode_B.cpp <- not included in the headers of the MainCode.cpp
MainCode_A.cpp
#include <iostream>
using namespace std;
int main ()
{
int choice = 0;
cin >> choice;
if (choice == 1)
{
"call routines from SubCode_A.cpp;" <- is there a possible code for this?
}
else if (choice == 2)
{
"call routines from SubCode_B.cpp;" <- is there a possible code for this?
}
return 0;
}
=================================
SubCode_A.cpp CODES
{
if (1) //i need to include if statement :)
cout >> "Hello World!!";
}
=================================
SubCode_B.cpp CODES
{
if (1) //i need to include if statement :)
cout >> "World Hello!!";
}
Make the code in e.g. SubCode_A.cpp a function, then declare this function in your main source file and call it. You of course have to build with all source files to create the final executable.
You can just use an #include statement.
Include instructs the compiler to insert the specified file at the #include point.
So your code would be
if (choice == 1)
{
#include "SubCode_A.cpp"
}
...
And you wouldn't need the extra braces in the SubCode_?.cpp files because they exist in MainCode.cpp
Of course, the compiler will only compile what is in the SubCode files at the time of compilation. Any changes to source that aren't compiled won't end up in your executable.
But mid source #includes doesn't lend itself to very readable code.
No
You have to compile both codes,
Declare an external function (e.g. extern void function (int);, in a header.
Compile those two files which will include this header.
Then in a 3rd file, where you use it just include the header.
BUT as you include all the 3 files in the compilation it will work.
This other post maybe useful : Effects of the extern keyword on C functions
It is not possible to call the code in another executable. It is possible for one application to expose an "api" (application programming interface) through a library or DLL which allows you to call some of the code that the application uses.
While compiling YOUR code, though, the compiler needs to know the "fingerprint" of the functions you are going to call: that is, what it returns and what arguments it takes.
This is done through a declaration or "prototype stub":
// subcode.h
void subCodeFunction1(); // prototype stub
void subCodeFunction3(int i, int j);
// subcode.cpp
#include <iostream>
void subCodeFunction1()
{
std::cout << "subCodeFunction1" << std::endl;
}
void subCodeFunction2()
{
std::cout << "subCodeFunction2" << std::endl;
}
void subCodeFunction3(int i, int j)
{
std::cout << "subCodeFunction1(" << i << "," << j << ")" << std::endl;
}
// main.cpp
#include "subcode.h"
int main() {
subCodeFunction1(); // ok
subCodeFunction2(); // error: not in subcode.h, comment out or add to subcode.h
subCodeFunction3(2, 5); // ok
return 0;
}
Related
I am a little bit new to cpp. And all the concepts of 'includes' tho are important are pretty new and vague forme. I have a few questions which are related to my main question . The main question is:. I have a program which is a file containing 'main' and other 5 classes let's call it 'PROG'. I put them all in one file using no h files at all. The program is running and all is good. The point is, I now have 'test file ' which should test my program. Test file is separated to h file and cpp file. Is there any way to run everything without changing my program 'PROG'?? I don't want to create h files to my 'PROG' . The problem is, the test file uses a few of the claseess written the program 'PROG'. I thought about writing 'includes' cpp in the test file and putting 'pragma once'. I don't know why it doesn't work. Doesn't pragma once work for ' cpp includes'??
Or basically can anyone answer the general question. Which is in short:. You have a file containing main and classes (which all in cpp file with no h file) . And you want to run it with another file (cpp+ h) but both files use each othrr. Which makes a circular use. Is there a way to run it ?
You might be able to write tests, however they will be run at an unspecified time either before or after your program runs, so won't be able to access std::cout etc. If your program uses any static objects, you won't be able to do this.
It will be much easier to move your main into a main.cpp that #includes definitions of your classes, and compile a separate test_main.cpp that instead runs your tests.
As a sketch of the former
class TestFailure{};
class RunAtStartup
{
template<typename Func>
RunAtStartup(Func f) { f(); }
}
extern double function_to_test(int arg);
static RunAtStartup run_function_to_test([]{
// arrange
int param = 0;
// act
double res = function_to_test(param);
// assert
if(res != 1.0) throw TestFailure();
});
Does this help?
PROG:
class C {
void f();
}
#ifndef TEST
void C::f() {
// implementation
}
#endif // TEST
TEST:
#define TEST
#include "main.cpp"
// Your test code here can have instances to class C
C c;
c.f();
But take cpp/h approach as anyone recommends, which is everywhere.
I'd highly recommend using headers, but if you really don't want to modify your original file, you can #include "main.cpp" from your test file and redefine the main symbol during the inclusion. This allows you to create your own main method for the test program.
In test.cpp:
#define main real_main
#include "mymain.cpp"
#undef main
int main(int argc, const char** argv) {
std::cout << "wah" << std::endl;
int fakeargc = 1;
const char* fakeargv[fakeargc] = { "hoo" };
real_main(fakeargc, fakeargv);
}
In main.cpp:
#include <iostream>
int main(int argc, const char** argv) {
std::cout << "hello world " << argv[0] << std::endl;
return 0;
}
I encountered this problem when I try to compile my code
I thought it might be caused by header files including each other. But as far as I can tell I did not find any issues with my header files
Error LNK1169 one or more multiply defined symbols
found Homework2 D:\05Development\04 C_C++\C\DS Alg
class\Homework2\Debug\Homework2.exe 1
also, there's an error telling me that function Assert() has been declared elsewhere.
Error LNK2005 "void __cdecl Assert(bool,class
std::basic_string,class
std::allocator >)"
(?Assert##YAX_NV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std###Z)
already defined in DataBase.obj Homework2 D:\05Development\04
C_C++\C\DS Alg class\Homework2\Homework2\dbTest.obj 1
here's the structure of my code:
function
void Assert(bool val, string s)
{
if (!val)
{
cout << "Assertion Failed!!: " << s << endl;
exit(-1);
}
}
is in Constants.h
A virtual class List includes Constants.h
#pragma once // List.h
#include "Constants.h"
An array list includes List class, in the AList class it calls the Assert function
#pragma once //AList.h
#include "List.h"
...
Assert((pos >= 0) && (pos < listSize), "Position out of range");
In the DataBase class I created a AList member
private:
AList<CData> set;
header looks like this:
#pragma once
#include "AList.h"
#include "CData.h"
and CData.h looks like this:
#pragma once
class CData
{
private:
std::string m_name;
int m_x;
int m_y;
public:
CData(std::string str = "null", int x = 0, int y = 0) : m_name(str), m_x(x), m_y(y) {}
// Helper functions
const std::string& GetName() const { return this->m_name; }
const int& GetX() const { return this->m_x; }
const int& GetY() const { return this->m_y; }
};
When you build your project, each .cpp file gets compiled separately into different object files. The once in #pragma once only applies to the compilation of a single .cpp file, not for the project as a whole. Thus if a .cpp file includes header A and header B, and header B also includes header A, then the second include of header A will be skipped.
However, if you have another .cpp file that includes A, A will be included in that object file again -- because #pragma once only works when compiling a single .cpp file.
An #include statement literally takes the content of the included file and "pastes" it into the file that included it. You can try this by looking at the output of the C preprocessor tool (cpp in the gcc toolchain). If you are using the gcc toolchain, you can try something like this to see the file after its includes have been applied:
cpp file.cpp -o file_with_includes.cpp
If you have a function in your header, like Assert in your example, the function gets replicated into each .cpp file you include it in.
If you have A.cpp and B.cpp, that both include your Constants.h file, each object file (.o or .obj depending on your environment) will include a copy of your Assert function. When the linker combines the object files to create a binary, both object files will declare that they provide the definition for Assert, and the linker will complain, because it doesn't know which one to use.
The solution here is either to inline your Assert function, like this:
inline void Assert(bool val, string s)
{
if (!val)
{
cout << "Assertion Failed!!: " << s << endl;
exit(-1);
}
}
or to provide its body in its own .cpp file, leaving only the function prototype in the header.
Constants.h:
void Assert(bool val, string s);
Constants.cpp:
void Assert(bool val, string s)
{
if (!val)
{
cout << "Assertion Failed!!: " << s << endl;
exit(-1);
}
}
Mind you, the Standard Library also offers assert(), which works nicely too. (see https://en.cppreference.com/w/cpp/error/assert).
#include <cassert>
...
assert(is_my_condition_true());
assert(my_variable > 23);
// etc..
Just keep in mind that the assert declared in cassert only works when compiling for Debug, and gets compiled out when building for Release (to speed up execution), so don't put any code in assert that has side effects.
#include <cassert>
...
// Don't call functions with side effects.
// Thus function decreases a "count" and returns the new value
// In Release builds, this line will disappear and the decrement
// won't occur.
assert(myclass.decrement_count() > 0);
This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
C++: Easiest way to access main variable from function?
I need to get my variable "input" from my main function in a.cpp to another function named check in b.cpp. I looked into it on Google and this forum/thingy, and I found you could do it with global variables using extern, but that's it's also bad to use those and I couldn't find an answer to what an alternative is? How should I transfer the data in the variable to the other function without using globals?
Code of how I got arguments to work.
(What I'm trying to do here is a console "manager" for solutions of project Euler which I can call to solve/view via input, I started working on the code 40 mins ago.)
main.cpp
#include <iostream>
#include <windows.h>
#include "prob.h"
using namespace std;
int check(string x);
int main()
{
string input = "empty";
clear();
cout << "Welcome to the Apeture Labs Project Euler Console! (ALPEC)" << endl << endl;
cout << "We remind you that ALPEC will never threaten to stab you" << endl;
cout << "and, in fact, cannot speak. In the event that ALPEC does speak, " << endl;
cout << "we urge you to disregard its advice." << endl << endl;
cin >> input;
cin.get();
check(input);
cout << input << endl;
cin.get();
return 0;
}
prob.h
#ifndef PROB_H_INCLUDED
#define PROB_H_INCLUDED
int main();
int clear();
int check();
int back();
int P1();
int P2();
int P3();
int P4();
#endif // PROB_H_INCLUDED
back.cpp
#include <iostream>
#include <windows.h>
#include "prob.h"
using namespace std;
int clear()
{
system( "#echo off" );
system( "color 09" );
system( "cls" );
return 0;
}
int check( string x )
{
if( x == "help" );
if( x == "empty" )
{
cout << "And.... You didn't enter anything..." << endl << endl;
}
else
{
cout << "Do you have any clue what you are doing? " << endl << endl;
}
return 0;
}
By passing the data as an function argument.
For example:
int doSomething(int passedVar)
{
}
int main()
{
int i = 10;
doSomething(i);
return 0;
}
Note that the function definition may reside even in a different cpp file. The main only needs to see the function declaration, and the linker shall link the function definition correctly.
Usually, one would add the function declaration in a header file and include the header file in main, while providing the function definition in another cpp file.
The code you show has number of problems:
You do not need to declare main in the header file.
Your function declaration and definition of check() do not match. Your header file says it takes no argument and you define a the function definition to take one argument. Obviously, they don't match. As they stand now they are two completely different functions.
As the compiler sees it you declared one function who's definition you never provided and you defined another function in the cpp file. Thus the function declared(one with no parameters) was never defined and hence the definition not found error.
Andrei Tita is absolutely correct. If you have a "value" in one module (e.g. "main()" in a.cpp), and you wish to use that value in a function (e.g. "foo()" in b.cpp) ... then just pass that value as a function argument!
As your programs become more sophisticated, you'll probably start using classes (instead of functions) .
Let we have a code in "luafunc.lua":
function foo(a, b)
return a + b
end
a = io.read('*n')
b = io.read('*n')
print (foo(a, b))
Let's try to use function foo from C++ file:
#include <iostream>
using namespace std;
extern "C"{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};
int main()
{
lua_State *lvm = lua_open();
luaL_openlibs(lvm);
luaL_loadfile(lvm, "luafunc.lua");
int a, b;
cin >> a >> b;
lua_pcall(lvm, 0, LUA_MULTRET, 0);
lua_getglobal(lvm, "foo");
lua_pushnumber(lvm, a);
lua_pushnumber(lvm, b);
if (lua_pcall(lvm, 2, 1, 0))
{
cout << "Error: " << lua_tostring(lvm, -1) << endl;
return 0;
}
cout << "The result is: " << lua_tonumber(lvm, -1) << endl;
lua_close(lvm);
return 0;
}
So, the problem is that this C++ code executes the whole luafunc.lua. Naturally I can remove reading part from lua-file and then from C++ only foo is executed. But can I use function foo from C++ even if there's other stuff in lua-file?
If you need to be able to use that function without also running that code, separate the code and function into two separate scripts, a script with foo in it and a script that loads that script and tests foo.
A function is not defined until the script containing it is executed. Executing that script will define foo and then run the other 3 lines as well.
When you load a file with loaL_loadfile (or any of the other load calls) the entire script is turned into a function; to execute it you have to call that function, with lua_pcall or whatever. Until then the script that defines foo is just an unnamed, unexecuted chunk of code on the stack.
There is no function to execute just part of a script, or execute only the function definitions.
can I use function foo from C++ even if there's other stuff in lua-file?
Yes.
Can you use it without executing the other parts of that file? No.
Lua functions are defined at runtime. Simply loading and compiling that script is not enough, you have to run the resulting chunk for foo to be defined in your Lua state.