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.
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;
}
So I am working on my first multiple file, non-toy, c++ project. I have a class that represents a multi-spectral image and all the information that goes along with it.
My problem is how to design the part of the program that loads and object of this class with a file from disk!
I don't think I need a class for this. Would switching to a functional approach be better for the file loading. This way I can have just a source file (.cpp) that has functions I can call while passing in pointers to the relevant objects that will be updated by the file accessed by the function.
I don't think static functions are what I want to use? As I understand it they(static functions) are for accessing static variables within a class, aren't they?
If I go the functional route, from main(), how do I access these functions? I assume I would include the functions .cpp file at the beginning of the main() containing file. From there how do I call the functions. Do i just use the function name or do I have to pre-pend something similar to what you have to pre-pend when including a class and then calling its methods.
Here is some example code of what I have tried and the errors I get.
OpenMultiSpec.cpp
#include <iostream>
void test(){
std::cout << "Test function accessed successfully" << std::endl;
}
main.cpp
int main(){
test();
return 1;
}
The error says " 'test' was not declared in this scope "
OpenMultiSpec.h
void test();
main.cpp
#include "OpenMultiSpec.h"
int main(){
test();
return 1;
}
If they're in two separate files, and in your case, one being a header, use
#include "OpenMultiSpec.h"
If you decide to only use one file (as your comment says above), you won't need #include for your header file. Just place your function declaration anywhere before you call it.
#include <iostream>
void test() {
std::cout << "Test function accessed successfully" << std::endl;
}
int main() {
test();
return 1;
}
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;
}
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) .
This is a small program :
#include <iostream>
using namespace std;
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
The error that i get here is :error C3861: 'f': identifier not found
If i place the function f above main I will get the desired output.
Why it is so ?
I was told that program execution begins at main. According to this the code should run in the first case also.
How does the compiler start reading the program?
The beginning of the compilation and the beginning of the execution of the program are two different things.
The execution starts from the main.
The compilation begins from the beginning of the file; the compiler don't "jump around" the file to find the needed pieces, but it reads the input in a linear fashion (I suspect that this related, among the other things, to the fact that the C++ grammar is really complicated).
When the compiler is at some point in parsing the file, it only knows what has been declared/defined up to that point1.
Because of this, function prototypes (and non-defining declarations in general) have been invented: the prototypes of all the functions defined in the file are put at the beginning of the file, typically after the #include directives or in a separated include file. The prototypes tell to the compiler that such functions will be defined later, and what is the function signature (i.e. name, parameters, return value).
The prototype is made as a normal function, but without the body, which is replaced by a semicolon2. For example, in your code you would write
void f();
before the main.
IIRC there are some relaxations to this rule that allow the compiler to "wait" for some declarations to make some template magic work, but this is not relevant here.
In a prototype is also common not to write the names of the parameters, leaving just their type (this can be done also in function definitions, but it doesn't make much sense there unless you have a formal parameter you don't use). Still, I prefer to leave the parameter names there as a form of documentation.
I was told that program execution begins at main.
And that's exactly the point.
The compiler starts from main, and then sees a call to f(), which it has not encountered so far (as it is defined afterwards), so it does not know what to do with it.
If you want to define f after main you can place a function prototype before, such as
#include <iostream>
using namespace std;
void f(); // <--- This tells the compiler that a function name f will be defined
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
To be able to call a function it must have been declared at some earlier point in the code. This is just a rule of the language designed to help compilers.
You can declare the function earlier with e.g.
void f();
...and then define it after main as you have done.
The compiler starts at the top and reads down to the bottom.
you'll need to have something like:
#include <iostream>
using namespace std;
void f();
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
No, the compiler needs to see at least a declaration of f() before it is used. A c(++) code file is a simple text file and must be read from begin to end by the compiler.
During the compilation process, when the compiler is evaluating main() it needs to know what f() is in advance to be able to generate the correct assembly code to call this function. That's why you need to put it before main() in this case.
As an alternative you can declare the prototype of f() before main() so the compiler knows it's a local function declared somewhere else on your file:
void f(); // prototype
int main()
{
// .. code ..
}
void f() // implementation of f()
{
// .. code ..
}