How can I import other files in Vala? - import

The question pretty much says it all- how could I import file2.vala to file1.vala?

You don't do it directly. If you run valac file1.vala file2.vala, it is as if you compiled them in one big file.
If you want to make them reusable, then you probably want a shared library. In which case, you compile one to produce a C header file and a VAPI definition:
valac --vapi file1.vapi -H file1.h --library libfile1.so file1.vala
The second one can then consume this:
valac --pkg file1 file2.vala
This assume that the VAPI file has been installed. If this is not the case, you'll need to pass --vapidir and the location where file1.vapi exists, probably .. Similarly, you'll need to inform the C compiler about where file1.h lives with -X -I/directory/containing, again, probably -X -I.. Finally, you'll need to tell the C linker where libfile1.so is via -X -L/directory/containing -X -lfile1. This is a little platform specific, and you can smooth the difference out using AutoMake, though this is a bit more involved. Ragel is the usual go-to project for how to use AutoMake with Vala.

just to supply apmasell:
you can use multiple files by using classes and public variables:
main.vala:
extern void cfunction(string text);
void main ()
{
first f = new first ();
f.say_something(f.mytext);
cfunction("c text\n");
}
class.vala:
public class first {
public string mytext = "yolo\n";
public first ()
{
stdout.printf("text from constructer in first\n");
}
public void say_something(string text)
{
stdout.printf("%s\n", text);
}
}
text.c:
#include <stdio.h>
void cfunction(const char *s)
{
puts("This is C code");
printf("%s\n", s);
}
compiles with: valac class.vala main.vala text.c
as you can see, you can even use C code

Related

How to force g++ to create C symbol name

I have a function called init in a cpp file, but when I compile it, g++ creates in the object file a symbol named _Z4initv, so when I link after with ld with the option -e init, obviously ld doesn't recognize the symbol init. Is there a way to create symbols name in C style with g++ ?
If you have a definition like e.g.
void init() { ... /* some code */ ... }
Then to inhibit name mangling you need to declare it as extern "C":
extern "C" void init() { ... /* some code */ ... }
If you have a declaration in a header file that you want to include in a C source file you need to check if you're including the header file in a C or C++ source file, using the __cplusplus macro:
#ifdef __cplusplus
extern "C"
#endif
void init(void);
Note that the function in the header file has to be declared with void in the argument list, if it doesn't take any arguments. That's because the declaration void init() means something else in C.

swig perl wrapper is not generating for class member functions

I have simple c++ class as below
//example.h
#include<iostream>
class example
{
public:
int member;
void display(){
std::cout<<"Hello from example class"<<std::endl;
}
};
//my example.i file is
%module example
%{
#include "example.h"
%}
%include "example.h"
after this I am running
pkgs/swig/2.0.8/bin/swig -c++ -perl5 example.i
but I don't see a wrapper defined for my display function in .pm module thus generated.
any working sample will be of great help.
Thanks,
Harish
even though I don't see a special wrapper for display method, I see something like below generated and it worked when i was trying to access it from perl
*display = *examplec::example_display;
my code to access the c++ class objects
use example;
$myObj =new example::example();
$myObj->{member} = 1000;
print $myObj->{member};
print "\n";
$myObj->display();
print "\nFinished";

How to dynamically add a key:value property to c++ class, then make it accessible as class.property

In Python I have a flag class that I have found very useful. I'm newbe to c++, and can not seem to replicate this python functionality in c++. Rather than put up c++ code that didn't work, here's what I am looking to replicate, and I need some suggestions on where to go, templates, virtual, or ??
The requirement is being able to dynamically alter the members of the class, in python it's modifying the dict element of the class it's self that enables this.
In python:
import sys
args = []
... loads up args[] with keys:values looping through sys.argv[] ... blah blah blah
class Flag:
def __ init __(self, **args):
self. __ dict __.update(args)
now we enable flag.dynamicproperty
flag = Flag(**dict(args))
An example of use:
$ python script.py somedesc1 someval1 somedesc2 someval2
What this does is enables me to pass in parameters, as above, from the command-line and assign any number of them on-the-fly, and make then accessible by a flag.property (eg flag.somedesc1) call which returns somval1. Another way to maybe think about this is dynamically adding a key:value property to a C++ class.
An example of use in python code :
if flag.somedesc1 != '10': print someval1
I can't seem to make a comparable c++ work. I've looked into polymorphism, but these have to be assigned dynamically and then be accessible as a property of the class.
Ideas??? Surely c++ can do this, I'm just not sure where to start.
Okay, here is the solution I worked out; haven't tested it yet, but should work close enough to fit my needs using this format
flag.find(filename)
enum { filename, workers, runtime };
class flag {
vector<string> helplist;
public:
int add(int argc, char *argv[], string flag, string value, string description) {
string flagvalue;
flagvalue = value;
helplist.push_back(description);
for (int i; i < argv.length(); i++) {
if (argv[i]==flag) {
flagvalue = argv[i+1];
}
}
}
void showhelp() {
for (int i; i < helplist.length(); i++) {
cout << helplist[i] << endl;
}
}
};
No, you can't do this in C++. In C++, the members of a class are defined 100% at compile time. You cannot add any at runtime. The way to do this in C++ would be to have a member variable that's a map<string,string> that holds the key/value pairs, and then have a function string getVariable(string) that returns the value in the dictionary for that key.

Strange LLVM warning: no previous prototype for function for

If I missed the prototype, XCode (LLVM) prompt me for error
no previous prototype for function for exceptionHandler
But why they are needed in my code below?
void exceptionHandler(NSException * exception); // Why this Line is needed?
void exceptionHandler(NSException * exception)
{
// ....
}
#implementation AppDelegate
- (void) applicationDidFinishLaunching:(UIApplication *)application
{
NSSetUncaughtExceptionHandler(&exceptionHandler);
...
From the GCC manual:
-Wmissing-prototypes (C and Objective-C only)
Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. The aim is to detect global functions that fail to be declared in header files.
Clang borrowed this option for GCC compatibility, and because it's useful (I would presume this of the Clang devs).
The option exists so you can prevent yourself from making a common mistake which may be easily avoided. It's nice to be explicit about visibility/linkage for clarity/intent's sake.
In short, you've asked the compiler to tell you when an unqualified definition does not match a declaration by enabling this option. You should either qualify that as extern and make it usable to others (e.g. put it in a header), or declare it static. If using C++ inline is also an option.
Of course, implicit visibility is well known, but I typically find the option useful in these scenarios:
1) I made a typo:
// file.h
extern void MONExceptionHandler(NSException * exception);
and
// file.m
void MONExceptionhandler(NSException * exception) {
…
2) I should be explicit about the symbol's visibility:
// file.m
static void MONExceptionHandler(NSException * exception) {
…
3) I forgot to #include the header which declared the function:
// file.h
extern void MONExceptionHandler(NSException * exception);
Warning:
// file.m
void MONExceptionHandler(NSException * exception) {
…
No Warning:
// file.m
#include "file.h"
void MONExceptionHandler(NSException * exception) {
…
So there's the rationale, history, and some examples - again, -Wmissing-prototypes is an option. If you trust yourself to work with it disabled, then do so. My preference is to be explicit, and to let programs detect potential and actual issues so I don't have to do it manually.
If you're declaring a function only for use within this file, prefix the declaration with the static keyword and the warning will go away. As it is, you're declaring a global function; theoretically it could be called from anywhere within your app. But as you've given it no prototype, nobody else could call it.
So the warning, as I understand it, is trying to make you clarify your intentions between static functions and global functions, and discourage you from declaring a global function when you meant to declare only a static one.
I think this is most useful for C++ code. For example I have header
class MyClass {
public:
void hello();
};
and .cpp file
void hello() {
cout << "hello";
}
And you will see the warning because there are no prototype for function void hello(). In case the correct implementation should be
void MyClass::hello() {
cout << "hello";
}
So this warning make sure you are implementing the function that you are aware of (not miss typed a name or different argument format).
That warning is alerting that you can't call your method from another method that is written above. In C, the order of the declaration/implementation minds a lot and gives the difference between something that you can access or you can't.

Using classes with the Arduino

I'm trying to use class objects with the Arduino, but I keep running into problems. All I want to do is declare a class and create an object of that class. What would an example be?
On Arduino 1.0, this compiles just fine:
class A
{
public:
int x;
virtual void f() { x=1; }
};
class B : public A
{
public:
int y;
virtual void f() { x=2; }
};
A *a;
B *b;
const int TEST_PIN = 10;
void setup()
{
a=new A();
b=new B();
pinMode(TEST_PIN,OUTPUT);
}
void loop()
{
a->f();
b->f();
digitalWrite(TEST_PIN,(a->x == b->x) ? HIGH : LOW);
}
There is an excellent tutorial on how to create a library for the Arduino platform. A library is basically a class, so it should show you how its all done.
On Arduino you can use classes, but there are a few restrictions:
No new and delete keywords
No exceptions
No libstdc++, hence no standard functions, templates or classes
You also need to make new files for your classes, you can't just declare them in your main sketch. You also will need to close the Arduino IDE when recompiling a library. That is why I use Eclipse as my Arduino IDE.
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230935955 states:
By default, the Arduino IDE and
libraries does not use the operator
new and operator delete. It does
support malloc() and free(). So the
solution is to implement new and
delete operators for yourself, to use
these functions.
Code:
#include <stdlib.h> // for malloc and free
void* operator new(size_t size) { return malloc(size); }
void operator delete(void* ptr) { free(ptr); }
This let's you create objects, e.g.
C* c; // declare variable
c = new C(); // create instance of class C
c->M(); // call method M
delete(c); // free memory
Regards,
tamberg
I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:
class AMLed
{
private:
uint8_t _ledPin;
long _turnOffTime;
public:
AMLed(uint8_t pin);
void setOn();
void setOff();
// Turn the led on for a given amount of time (relies
// on a call to check() in the main loop()).
void setOnForTime(int millis);
void check();
};
And here is the main source
AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
pinMode(_ledPin, OUTPUT);
}
void AMLed::setOn()
{
digitalWrite(_ledPin, HIGH);
}
void AMLed::setOff()
{
digitalWrite(_ledPin, LOW);
}
void AMLed::setOnForTime(int p_millis)
{
_turnOffTime = millis() + p_millis;
setOn();
}
void AMLed::check()
{
if (_turnOffTime != 0 && (millis() > _turnOffTime))
{
_turnOffTime = 0;
setOff();
}
}
It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html
To use, I simply do something like this in the .pde file:
#include "AM_Led.h"
#define TIME_LED 12 // The port for the LED
AMLed test(TIME_LED);
My Webduino library is all based on a C++ class that implements a web server on top of the Arduino Ethernet shield. I defined the whole class in a .h file that any Arduino code can #include. Feel free to look at the code to see how I do it... I ended up just defining it all inline because there's no real reason to separately compile objects with the Arduino IDE.
Can you provide an example of what did not work? As you likely know, the Wiring language is based on C/C++, however, not all of C++ is supported.
Whether you are allowed to create classes in the Wiring IDE, I'm not sure (my first Arduino is in the mail right now). I do know that if you wrote a C++ class, compiled it using AVR-GCC, then loaded it on your Arduino using AVRDUDE, it would work.