first,i changed the source code's extension to .cpp. And add them all into my C++ project.
the source files.jpg
second.im my main func,i code this:
namespace ClipsEmbed{
int main(){
Environment *theEnv;
theEnv = CreateEnvironment();
cout << Load(theEnv, "auto.clp");
Reset(theEnv);
Run(theEnv,-1L);
return 0;
}
}
after shooting some link and compile erro,it runs ok,but it just a CLIPS IDE,not my program.
just like this:
the result .jpg
i guess there is another main function,but i did not know where,so please help.how can i use the source code not the DLL in c++ project.
Your explanation is very confused and omitting details, but I think what you need is (at the simplest level):
namespace ClipsEmbed{
int main(){
Environment *theEnv;
theEnv = CreateEnvironment();
cout << Load(theEnv, "auto.clp");
Reset(theEnv);
Run(theEnv,-1L);
return 0;
}
}
int main () { return ClipsEmbed::main(); }
The main() is inside the ClipsEmbed namespace, so to satisfy the linker you need a plain main() in the global namespace, so the simplest solution is as illustrated, calling the namespace's main() from the global main().
Following feedback:
extern "C" int main () { return ClipsEmbed::main(); }
Might help?
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 have a simple .cpp file that looks like this:
void showMenu()
{
std::cout << "Hi!";
}
int main()
{
showMenu();
return 0;
}
In addition, I have an empty google-test that looks like this:
TEST(Name, SubName)
{
}
When I try to compile, I get:
multiple definition of `showMenu()'
and:
multiple definition of `main()'
errors.
How do I set my configurations so that I would be able to run my main when I went to, and my google-test when I want to, without them clashing into each other?
The googletest library already contains a definition for main().
To solve that, separate your definitions for showMenu() out into another library, and link that one to your testrunner and productive executable separately.
And don't #include your .cpp file with the test code.
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.
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;
}
A few days back, I came across this piece of C++ code, though I can't paste the code itself, I could recreate the problem with some sample code.
First, the file, namespace.h:
#include <iostream>
using namespace std;
namespace useless{
class X {
int m_myint;
static X *m_foobar;
X* getPrivVal(void);
public:
int getMember(void);
X* getStaticVal(void);
};
}
Next, namespace.cpp:
#include "namespace.h"
extern "C"{
namespace useless{
X* X::m_foobar = NULL;
X* X::getPrivVal(void){
if(m_foobar == NULL)
m_foobar = new X;
return(m_foobar);
}
}
}
namespace useless {
int X::getMember(void){
if(m_myint == 0)
m_myint = 1;
return(m_myint);
}
X* X::getStaticVal(void){
return(getPrivVal());
}
}
using namespace useless;
int main(void){
X y;
cout << "The int value is " << y.getMember() << endl;
cout << "The value of the static member is " << y.getStaticVal() << endl;
return(0);
}
This code compiled and linked fine when I used g++ 3.4.3, but gives the following error when I use g++ 4.x, I have tried with GCC 4.6.1 as well GCC 4.2.1. Have tried it on Linux as well as Mac, same results.
This is the error(Suse):
g++ -o namespace namespace.cpp
namespace.h:8:15: error: previous declaration of useless::X*
useless::X::m_foobar with C++ linkage
namespace.cpp:5:11: error: conflicts with new declaration with C linkage
Can someone please shed some light on what the legacy C++ code was looking to do, could this have been a hack or workaround to get around an old problem that I am not aware of any longer. Ohh by the way, the method inside the extern "C" is called by C++ code and not any C code as I initially suspected.
FYI, this is legacy code now, may have been written in 2001/2002 period.
Thanks guys. I have gone ahead and got rid of the extern "C" with no major impact.
#Bjorn Pollex : The guy who wrote that code is long gone.
The extern "C" directive has two effects, it disables mangling when possible and uses the C calling convention. In this particular case, because there is a namespace in between, name mangling cannot be disabled, so it could have been added to force a particular calling convention.
The code is actually wrong in that the declaration does not force extern "C" but the definition does, which is incorrect. Consider that if the compiler just followed the directive as shown, the caller would use C++ naming and calling conventions, while the function would be using the C variant, if the two differ the result will be undefined behavior.
Seems like an attempt to generate the variables witout C++ name mangling. That's one part of using extern "C".
The newer compiler obviously realizes that it really doesn't work.
If you have a piece of C++ code that you want to call from a module written in another language (C, FORTRAN or whatever), you want to turn off C++ name mangling.
Edit:
The really weird thing is that they did it on the definition but not on the declaration. It's a wonder that it ever compiled