Xcode duplicate symbol error - iphone

I am getting "Apple Mach-O Linker (Id) Error":
ld: duplicate symbol _matrixIdentity in /BlahBlah/Corridor.o and /Blahblah/Drawable.o for architecture i386
The class "Corridor" is extending the class "Drawable" and "_matrixIdentity" is defined and implemented in a file "Utils.h". Here are top lines from my header files:
Drawable.h
#import <Foundation/Foundation.h>
#import "Utils.h"
#interface Drawable : NSObject
...
Corridor.h
#import <Foundation/Foundation.h>
#import "Drawable.h"
#interface Corridor : Drawable
...
I have already checked if there are any ".m" imports instead of ".h", everything is correct. Any idea, what could cause this problem?
EDIT: posting code from "Utils.h"
#import <Foundation/Foundation.h>
...
#pragma mark -
#pragma mark Definitions
typedef float mat4[16];
#pragma mark -
#pragma mark Functions
void matrixIdentity(mat4 m)
{
m[0] = m[5] = m[10] = m[15] = 1.0;
m[1] = m[2] = m[3] = m[4] = 0.0;
m[6] = m[7] = m[8] = m[9] = 0.0;
m[11] = m[12] = m[13] = m[14] = 0.0;
}
...
I am only referencing to "mat4" definition in my both classes' methods. Also, "matrixIdentity" is just the first function in this file, may be the problem is not in implementation.

C/C++/Objective-C diff with Java, C#, Ruby, Python...
Divide files.
header & mm
Do not use #include (may include many times)
Use #import... (include once)
Utils.h
#ifndef __utils_h__ // <<< avoid multiple #include
#define __utils_h__ // <<< avoid multiple #include
#import <Foundation/Foundation.h>
...
#pragma mark -
#pragma mark Definitions
typedef float mat4[16];
#pragma mark -
#pragma mark Functions
extern void matrixIdentity(mat4 m);
#endif // __utils_h__ <<< avoid multiple #include
Utils.mm
#import "Utils.h"
void matrixIdentity(mat4 m)
{
m[0] = m[5] = m[10] = m[15] = 1.0;
m[1] = m[2] = m[3] = m[4] = 0.0;
m[6] = m[7] = m[8] = m[9] = 0.0;
m[11] = m[12] = m[13] = m[14] = 0.0;
}
...

Two solutions to your problem:
Declare only void matrixIdentity(mat4 m); in the header file and then implment the actual code in a corresponding c/m file.
Make your function in the header file inline (that's the technique Apple uses)
inline void matrixIdentity(mat4 m) { ...

From your description, utils.h declares and implements a variable, the implementation of which is compiled in corridor.h and Drawable.h by virtue of utils.h being included in both (indirectly through Drawable.h in the case of Corridor.h).
Thus both compilation units contain an implementation for _matrixIdentity, and the linker complains.
Move the implementation of _matrixIdentity into a new module utils.m to ensure there is only one definition of the symbol.

Use -force_load for one library in Other linker flags .. that solved the prob for me once

In my case, I was implementing a function in the header file itself. Adding a static inline keyword before the function fixed the error for me.

Related

print floats from audio input callback function

I'm working on a university project that involves a lot of programming in C, especially with Portaudio & ALSA. At the moment i'm trying to make a callback function to pass audio through, standard input/output job. I was wondering if anybody could tell me how to print the floats from my inputBuffer to display in real time in the terminal? Here is the internal structure of my callback function so far.
Thanks very much for your help in advance!
#define SAMPLE_RATE (44100)
#define PA_SAMPLE_TYPE paFloat32
#define FRAMES_PER_BUFFER (64)
typedef float SAMPLE;
static int audio_callback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
SAMPLE *out = (SAMPLE*)outputBuffer;
const SAMPLE *in = (const SAMPLE*)inputBuffer;
unsigned int i;
(void) timeInfo; /* Prevent unused variable warnings. */
(void) statusFlags;
(void) userData;
if( inputBuffer == NULL )
{
for( i=0; i<framesPerBuffer; i++ )
{
*out++ = *in++; /* left - clean */
*out++ = *in++; /* right - clean */
}
}
return paContinue;
}

USART of pic18f4550

I'm working on PIC18f4550. I want it to communicate through USART. I'm able to transmit a character but not able to receive any data. I check all the SFR's and r ri8 according to me. I'm using mplab c18 v3.46 compiler and MPLAB v8.40.
#include <p18f4550.h>
#include<usart.h>
#pragma config VREGEN = OFF // Voltage regulator USB , is Suspended
#pragma config WDT = OFF // Watchdog timer is suspended
#pragma config PLLDIV = 1 // Internal Oscillator engaged
#pragma config MCLRE = ON
#pragma config WDTPS = 32768
#pragma config CCP2MX = ON
#pragma config PBADEN = OFF
#pragma config CPUDIV = OSC1_PLL2
#pragma config USBDIV = 2
#pragma config FOSC = INTOSCIO_EC
#pragma config FCMEN = OFF
#pragma config IESO = OFF
#pragma config PWRT = OFF
#pragma config BOR = OFF
#pragma config BORV = 3
#pragma config LPT1OSC = OFF
#pragma config STVREN = ON
#pragma config LVP = OFF
#pragma config ICPRT = OFF
#pragma config XINST = OFF
#pragma config DEBUG = OFF
#pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF
#pragma config CPB = OFF
#pragma config CPD = OFF
#pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF
#pragma config WRTC = OFF
#pragma config WRTB = OFF
#pragma config WRTD = OFF
#pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF
#pragma config EBTRB = OFF
#define a PORTD
int i,j;
unsigned char serial_data;
extern void delay(int);
extern void tx_data(unsigned char);
extern unsigned char rx_data(void);
void tx_data(unsigned char data1)
{
TXREG=data1;
while(PIR1bits.TXIF==0);
}
unsigned char rx_data(void)
{
while(PIR1bits.RCIF==0); // Wait until RCIF gets low
return RCREG;
}
void main(void)
{
OSCCON=0x74;
TRISD= 0x00;
TRISC= 0x80;
OpenUSART(USART_TX_INT_OFF & USART_RX_INT_ON & USART_ASYNCH_MODE &USART_EIGHT_BIT & USART_CONT_RX & USART_BRGH_LOW, 12);
RCON=0x90;
INTCON=0xC0;
IPR1=0x00;
BAUDCON=0x00;
RCSTA=0x90;
tx_data('o'); // Transmit the same data back to PC
serial_data=rx_data(); // Receive data from PC
tx_data('k');
}
I found this code on net and modified accordingly. It transmits 'o' and never respond again for 'k'
Off the top of my head... I don't use the C18 compiler, but if it acts like any regular compiler does, then it's probably due to something like this:
You activate the UART receive interrupt with the USART_RX_INT_ON flag, then you enable the GIEH/GIEL bits in INTCON.
But you don't provide an interrupt service routine. So my guess is that, sitting at the interrupt vector locations (typically PROGRAM ADDRESS 0x08 and 0x18 for PIC18), are NOP assembly instructions. And so when a Receive event hits, it jumps to the high priority interrupt vector at address 0x18 (because IPEN is enabled and IPR1 is cleared), and then it just overflows to whatever next valid instruction is from there, because there are no GOTO instruction at that vector address to properly make it go to a specific ISR function, and then properly return to the last known code location when the interrupt event occured...

getting libstruct to work in matlab for dll pointer argument

I'm trying to call a dll function in matlab. I have a C++ struct as shown in sixense.h:
typedef struct _sixenseControllerData {
float pos[3];
float rot_mat[3][3];
float joystick_x;
float joystick_y;
float trigger;
...
} sixenseControllerData;
and functions I could call:
SIXENSE_EXPORT int sixenseInit( void );
SIXENSE_EXPORT int sixenseGetAllNewestData( sixenseAllControllerData * );
I can easily get this to work with calllib('sixense','sixenseInit') since there is no input, but for the function sixenseGetAllNewestData I need to have a struct pointer. I realize that libstruct is what I need to use. However, I don't seem to be doing it right.
So I tried libstruct like so:
libstruct('sixenseControllerData')
and I get the error:
??? Error using ==> feval
Undefined function or variable 'lib.sixenseControllerData'.
Error in ==> libstruct at 15
ptr=feval(['lib.' structtype]);
EDIT: here is my current unedited proto file:
http://pastebin.com/PemmmMqF
the full header file is available here:
https://github.com/rll/sixense/blob/master/include/sixense.h
For C structures, loadlibrary generates types named: s_{NAME} where {NAME} is the name of the structure. In your case we create a pointer as:
s = libstruct('s_sixenseControllerData');
We can see this fact by instructing MATLAB to generate a prototype file:
>> loadlibrary('sixense', 'sixense.h', 'proto','sixense_proto')
A prototype file is a file of MATLAB commands which we can modify and use in place of a header file. In this case, the file will contain something like:
sixense_proto.m
...
structs.s_sixenseControllerData.members = struct('pos', 'single#3', 'rot_mat', 'single#9', 'joystick_x', 'single', 'joystick_y', 'single', 'trigger', 'single', 'buttons', 'uint32', 'sequence_number', 'uint8', 'rot_quat', 'single#4', 'firmware_revision', 'uint16', 'hardware_revision', 'uint16', 'packet_type', 'uint16', 'magnetic_frequency', 'uint16', 'enabled', 'int32', 'controller_index', 'int32', 'is_docked', 'uint8', 'which_hand', 'uint8', 'hemi_tracking_enabled', 'uint8');
structs.s_sixenseAllControllerData.members = struct('controllers', 's_sixenseControllerData#4');
....
Unfortunately, a limitation of loadlibrary is that it does not support nested structure very well, especially if a structure contains a pointer to another structure (or an array in this case):
Nested structures or structures containing a pointer to a structure are
not supported. However, MATLAB can access an array of
structures created in an external library.
So you will not be able to directly create the sixenseAllControllerData structure on the MATLAB side, which is defined in the C header file as:
typedef struct _sixenseAllControllerData {
sixenseControllerData controllers[4];
} sixenseAllControllerData;
According to the following discussion, one workaround is to "unroll"/"flatten" the array into separate variables. You can either do this in a copy of the header file, or making the changes in the generated prototype file (which I think is the preferred way). You can do this without having to recompile the shared library.
In your case, change the nested structure in the generated sixense_proto.m file into:
structs.s_sixenseAllControllerData.members = struct(...
'controllers1', 's_sixenseControllerData', ...
'controllers2', 's_sixenseControllerData', ...
'controllers3', 's_sixenseControllerData', ...
'controllers4', 's_sixenseControllerData');
Now we can create a pointer to this structure, and call the C method:
s = libstruct('s_sixenseAllControllerData');
s.controllers1 = libstruct('s_sixenseControllerData');
s.controllers2 = libstruct('s_sixenseControllerData');
s.controllers3 = libstruct('s_sixenseControllerData');
s.controllers4 = libstruct('s_sixenseControllerData');
out = calllib('sixense', 'sixenseGetAllNewestData', s);
get(s)
A completely different solution is to write a MEX-function to interface with the library. It is just like any other C/C++ code, only using mxArray and the MX-API to interface with MATLAB...
Example:
To test the above, I created a simple DLL with similar structures, and implemented the above solution. Here is the code if someone wants to test it:
helper.h
#ifndef HELPER_H
#define HELPER_H
#ifdef _WIN32
#ifdef EXPORT_FCNS
#define EXPORTED_FUNCTION __declspec(dllexport)
#else
#define EXPORTED_FUNCTION __declspec(dllimport)
#endif
#else
#define EXPORTED_FUNCTION
#endif
#endif
mylib.h
#ifndef MYLIB_H
#define MYLIB_H
#include "helper.h"
typedef struct _mystruct {
int pos[3];
double value;
} mystruct;
typedef struct _mystruct2 {
mystruct arr[2];
int num;
} mystruct2;
EXPORTED_FUNCTION void myfunc(mystruct *);
EXPORTED_FUNCTION void myfunc2(mystruct2 *);
#endif
mylib.c
#define EXPORT_FCNS
#include "helper.h"
#include "mylib.h"
void myfunc(mystruct *s)
{
s->pos[0] = 10;
s->pos[1] = 20;
s->pos[2] = 30;
s->value = 4.0;
}
void myfunc2(mystruct2 *s)
{
int i;
for(i=0; i<2; i++) {
myfunc(&(s->arr[i]));
}
s->num = 99;
}
After compiling the above into a DLL, we generate the initial prototype file:
loadlibrary('./mylib.dll', './mylib.h', 'mfilename','mylib_proto')
unloadlibrary mylib
I edit the prototype file as described before:
function [methodinfo,structs,enuminfo,ThunkLibName] = mylib_proto()
MfilePath = fileparts(mfilename('fullpath'));
ThunkLibName = fullfile(MfilePath,'mylib_thunk_pcwin64');
enuminfo = [];
structs = [];
structs.s_mystruct.members = struct('pos','int32#3', 'value','double');
structs.s_mystruct2.members = struct('arr1','s_mystruct', ...
'arr2','s_mystruct', 'num','int32');
ival = {cell(1,0)};
methodinfo = struct('name',ival, 'calltype',ival, 'LHS',ival, ...
'RHS',ival, 'alias',ival, 'thunkname',ival);
methodinfo.thunkname{1} = 'voidvoidPtrThunk';
methodinfo.name{1} = 'myfunc';
methodinfo.calltype{1} = 'Thunk';
methodinfo.LHS{1} = [];
methodinfo.RHS{1} = {'s_mystructPtr'};
methodinfo.thunkname{2} = 'voidvoidPtrThunk';
methodinfo.name{2} = 'myfunc2';
methodinfo.calltype{2} = 'Thunk';
methodinfo.LHS{2} = [];
methodinfo.RHS{2} = {'s_mystruct2Ptr'};
end
Now we can finally invoke functions exposed by the DLL:
%// load library using proto file
loadlibrary('./mylib.dll', #mylib_proto)
%// call first function with pointer to struct
s = struct('pos',[0,0,0], 'value',0);
ss = libstruct('s_mystruct',s);
calllib('mylib', 'myfunc', ss)
get(ss)
%// call second function with pointer to struct containing array of struct
xx = libstruct('s_mystruct2');
xx.arr1 = libstruct('s_mystruct');
xx.arr2 = libstruct('s_mystruct');
calllib('mylib', 'myfunc2', xx)
get(xx)
%// clear references and unload library
clear ss xx
unloadlibrary mylib

Finding and returning the distance between two coordinates

I'm sort of a newbie--please don't hate.
The method compiles, but I'm not sure how to actually retrieve the float value (i.e. the distance between the two points) that the method returns (or should return rather).
-(float)findDistanceBetween:(Coordinate *)a and:(Coordinate *)b
{
//distance formula:
//sqrt( (x2 - x1)^2 + (y2 - y1)^2 )
float resultDistance;
resultDistance = sqrt( pow((b.latitude - a.latitude), 2) + pow((b.longitude - a.longitude), 2));
return resultDistance;
}
//Somewhere else...
float theDistanceBetween;
//Below is incorrect:
theDistanceBetween = [findDistanceBetween: location1 and: location2];
Thanks
So, if your error is that self is undeclared, that means that you are trying to send -findDistanceBetween:and: from outside the context of the class that declares it.
When you do something like [obj method], that demands a few things:
That obj is an instance of an Objective-C class.
That the class of obj implements -method.
So, if the receiver of your message is self, that means that:
You need to be within the context of a class's implementation for the self to be implicitly declared.
The class you're in needs to be the same one as implements -findDistanceBetween:and:.
Methods are not just a shiny replacement for functions that can be called in any context. They can be called on objects that implement them (technically not "called" in Smalltalk-like languages such as Objective-C, but that's for another time).
I suspect that you have larger design issues as well. What kind of object is -findDistanceBetween:and: meant to be sent to? If it is a utility method in a class that does something bigger, then it should be a class method (+findDistanceBetween:and:), since it does not need to know about any specific instance. If, however, it is a method on Coordinate, then it'd be better expressed as -findDistanceTo:, which would take a coordinate parameter. And then the implementation of that would compare the provided coordinate parameter with self.
findDistanceBetween:and: is an instance method; it's something a particular instance of your class can do.
So you'd call it like:
theDistanceBetween = [self findDistanceBetween: location1 and: location2];
Which means "send the message 'findDistanceBetween: location1 and: location2' to the object 'self', and store the result to theDistanceBetween". self just means the current object; it's an object sending a message to itself.
Is findDistanceBetween:and: defined in an #implementation block? Your code should look something like
// in the .h file
#interface MyClass : NSObject
// declaration of the method
- (float)findDistanceInBetween:(Coordinate *)a and:(Coordinate *)b;
#end
// in the .m file
#implementation MyClass
// definition of the method
- (float)findDistanceBetween:(Coordinate *)a and:(Coordinate *)b {
return sqrt(powf(a.x - b.x, 2.f) + powf(a.y - b.y, 2.f));
}
#end
// then somewhere else that needs to calculate the difference:
// (assume coord_a and coord_b already exist)
// create an instance of MyClass
MyClass *myInstance = [[MyClass alloc] init];
// send the `findDistanceBetween:and:` message to the instance
float distance = [myInstance findDistanceBetween:coord_a and:coord_b];
// when you're done with the instance, you need to clean up
[myInstance release];
It may make more sense to put these types of methods on the Coordinate class itself so you can just do something like:
Coordinate *coord_a = <get the coordinate from somewhere>;
Coordinate *coord_b = <get the coordinate from somewhere>;
float distance = [coord_a distanceFrom:coord_b];
float angle = [coord_a angleTo:coord_b];
Don't worry about anyone hating, we were all new at this once. :)
Try to add -(float)findDistanceBetween:(Coordinate *)a and:(Coordinate *)b; to your .h file
As mentioned by Ferruccio above latitude and longitude are in degrees and you method should be returning some form of distance. Below are some methods that will calculate distance as well as bearing between 2 CLLocationCoordinate2Ds.
- (double)degreeToRadian:(double)degree{
return (degree * (M_PI/180.0));
}
- (double)radianToDegree:(double)radian{
return (radian *(180.0/M_PI));
}
-(double) distanceFromCordinate:(CLLocationCoordinate2D)fromCoord to:(CLLocationCoordinate2D)toCoord {
double radiusOfEarth = 6371.0;
double fromLongitude, fromLatitude, toLongitude, toLatitude;
double _deltaLongitude, _deltaLatitude;
double a, c;
fromLongitude = [self degreeToRadian:fromCoord.longitude];
fromLatitude = [self degreeToRadian:fromCoord.latitude];
toLongitude = [self degreeToRadian:toCoord.longitude];
toLatitude = [self degreeToRadian:toCoord.latitude];
_deltaLongitude = toLongitude - fromLongitude;
_deltaLatitude = toLatitude - fromLatitude;
a = (sin(_deltaLatitude/2) * sin(_deltaLatitude/2)) + ( cos(fromLatitude) * cos(toLatitude) * (sin(_deltaLongitude/2) * sin(_deltaLongitude/2)) );
c = 2 * atan2( sqrt(a), sqrt(1-a));
return (radiusOfEarth * c);
}
- (double)bearingFromCordinate:(CLLocationCoordinate2D)fromCoord to:(CLLocationCoordinate2D)toCoord{
double fromLatitude, toLatitude;
double _deltaLongitude;
double x, y;
double bearing;
fromLatitude = [self degreeToRadian:fromCoord.latitude];
toLatitude = [self degreeToRadian:toCoord.latitude];
deltaLongitude = [self degreeToRadian:(toCoord.longitude - fromCoord.longitude)];
y = sin(deltaLongitude) * cos(toLatitude);
x = (cos(fromLatitude) * sin(toLatitude)) - (sin(fromLatitude) * cos(toLatitude) * cos(deltaLongitude));
bearing = atan2(y,x);
return fmod(([self radianToDegree:bearing] + 360.0), 360.0) ;
}

Creating Threaded callbacks in XS

EDIT: I have created a ticket for this which has data on an alternative to this way of doing things.
I have updated the code in an attempt to use MY_CXT's callback as gcxt was not storing across threads. However this segfaults at ENTER.
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#ifndef aTHX_
#define aTHX_
#endif
#ifdef USE_THREADS
#define HAVE_TLS_CONTEXT
#endif
/* For windows */
#ifndef SDL_PERL_DEFINES_H
#define SDL_PERL_DEFINES_H
#ifdef HAVE_TLS_CONTEXT
PerlInterpreter *parent_perl = NULL;
extern PerlInterpreter *parent_perl;
#define GET_TLS_CONTEXT parent_perl = PERL_GET_CONTEXT;
#define ENTER_TLS_CONTEXT \
PerlInterpreter *current_perl = PERL_GET_CONTEXT; \
PERL_SET_CONTEXT(parent_perl); { \
PerlInterpreter *my_perl = parent_perl;
#define LEAVE_TLS_CONTEXT \
} PERL_SET_CONTEXT(current_perl);
#else
#define GET_TLS_CONTEXT /* TLS context not enabled */
#define ENTER_TLS_CONTEXT /* TLS context not enabled */
#define LEAVE_TLS_CONTEXT /* TLS context not enabled */
#endif
#endif
#include <SDL.h>
#define MY_CXT_KEY "SDL::Time::_guts" XS_VERSION
typedef struct {
void* data;
SV* callback;
Uint32 retval;
} my_cxt_t;
static my_cxt_t gcxt;
START_MY_CXT
static Uint32 add_timer_cb ( Uint32 interval, void* param )
{
ENTER_TLS_CONTEXT
dMY_CXT;
dSP;
int back;
ENTER; //SEGFAULTS RIGHT HERE!
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSViv(interval)));
PUTBACK;
if (0 != (back = call_sv(MY_CXT.callback,G_SCALAR))) {
SPAGAIN;
if (back != 1 ) Perl_croak (aTHX_ "Timer Callback failed!");
MY_CXT.retval = POPi;
} else {
Perl_croak(aTHX_ "Timer Callback failed!");
}
FREETMPS;
LEAVE;
LEAVE_TLS_CONTEXT
dMY_CXT;
return MY_CXT.retval;
}
MODULE = SDL::Time PACKAGE = SDL::Time PREFIX = time_
BOOT:
{
MY_CXT_INIT;
}
SDL_TimerID
time_add_timer ( interval, cmd )
Uint32 interval
void *cmd
PREINIT:
dMY_CXT;
CODE:
MY_CXT.callback=cmd;
gcxt = MY_CXT;
RETVAL = SDL_AddTimer(interval,add_timer_cb,(void *)cmd);
OUTPUT:
RETVAL
void
CLONE(...)
CODE:
MY_CXT_CLONE;
This segfaults as soon as I go into ENTER for the callback.
use SDL;
use SDL::Time;
SDL::init(SDL_INIT_TIMER);
my $time = 0;
SDL::Timer::add_timer(100, sub { $time++; return $_[0]} );
sleep(10);
print "Never Prints";
Output is
$
it should be
$ Never Prints
Quick comments:
Do not use Perl structs (SV, AV, HV, ...) outside of the context of a Perl interpreter object. I.e. do not use it as C-level static data. It will blow up in a threading context. Trust me, I've been there.
Check out the "Safely Storing Static Data in XS" section in the perlxs manpage.
Some of that stuff you're doing looks rather non-public from the point of view of the perlapi. I'm not quite certain, though.
$time needs to be a shared variable - otherwise perl works with separate copies of the variable.
My preferred way of handling this is storing the data in the PL_modglobal hash. It's automatically tied to the current interpreter.
We have found a solution to this using Perl interpreter threads and threads::shared. Please see these
Time.xs
Also here is an example of a script using this code.
TestTimer.pl