Showing posts with label C++. Show all posts
Showing posts with label C++. Show all posts

Friday, November 6, 2015

Shared Libraries Demo *.so file.



Ref 1 cmd line to generate *.so on stackoverflow
Ref 2 stackflow post ld --verbose -llibxxx

testsomain is smaller when not compiled with testso.c 
[q.yang@fedora20 Trash]$ gcc testsomain.c -o testsomain -L./ -ltestso
It's bigger when compiled with testso.c. It's one of the benefit of using dynamic library.
[q.yang@fedora20 Trash]$ gcc testsomain.c testso.c -o testsomain
testsomain.c
#include 
#include "testso.h"

int main(void)
{
  printf("Testing calling function in *.so \n");
  Ext_PrintHello();
}
testso.c
#include 

void Ext_PrintHello(void)
{
  printf("%s Invoked from external module.\n",__func__);
}
testso.h
//#error "this file has been included here"

void Ext_PrintHello(void);
Compile to generate dynamic library:
Note: MUST use -fPIC option PositionIndependantCode(PIC)
*.so file name must be libxxnamexx.so, cannot be xxnamexx.so
[q.yang@fedora20 Trash]$ gcc -shared -fPIC -o libtestso.so testso.c
Compile main program to load dynamic library *.so
[q.yang@fedora20 Trash]$ gcc testsomain.c -o testsomain -L./ -ltestso
Set load library search path
[q.yang@fedora20 Trash]$ LD_LIBRARY_PATH=./
[q.yang@fedora20 Trash]$ export LD_LIBRARY_PATH
Run program
[q.yang@fedora20 Trash]$ ./testsomain 
Testing calling function in *.so 
Ext_PrintHello Invoked from external module.
Checking so file dependencies $ldd and file info $file. (Running for i686 or ARM)
duser@10.1.1.8:~/Trash$ file libtestso.so 
libtestso.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, BuildID[sha1]=0xf54c8aad49c8dfd0220885eab40fe703c0e5495b, not stripped

duser@10.1.1.8:~/Trash$ ldd libtestso.so 
 libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb754b000)
 /lib/ld-linux.so.2 (0xb770f000)

We can also use linker $ld to check where system default search path for *.so shared library files. Given libtestso.so [Ref 2]
duser@10.1.1.8:~/Trash$ld -L./ -ltestso --verbose

..................
..................
==================================================
attempt to open /usr/i686-linux-gnu/lib32/libtestso.so failed
attempt to open /usr/i686-linux-gnu/lib32/libtestso.a failed
attempt to open /usr/local/lib32/libtestso.so failed
attempt to open /usr/local/lib32/libtestso.a failed
attempt to open /lib32/libtestso.so failed
attempt to open /lib32/libtestso.a failed
attempt to open /usr/lib32/libtestso.so failed
attempt to open /usr/lib32/libtestso.a failed
attempt to open /usr/local/lib/i386-linux-gnu/libtestso.so failed
attempt to open /usr/local/lib/i386-linux-gnu/libtestso.a failed
attempt to open /usr/local/lib/libtestso.so failed
attempt to open /usr/local/lib/libtestso.a failed
attempt to open /lib/i386-linux-gnu/libtestso.so failed
attempt to open /lib/i386-linux-gnu/libtestso.a failed
attempt to open /lib/libtestso.so failed
attempt to open /lib/libtestso.a failed
attempt to open /usr/lib/i386-linux-gnu/libtestso.so failed
attempt to open /usr/lib/i386-linux-gnu/libtestso.a failed
attempt to open /usr/lib/libtestso.so failed
attempt to open /usr/lib/libtestso.a failed
/usr/bin/ld.bfd.real: cannot find -ltestso
If we tell the load library path via -L option. Linker will find it.
duser@10.1.1.8:~/Trash$ ld -L./ -ltestso --verbose
....................
....................
==================================================
attempt to open .//libtestso.so succeeded
-ltestso (.//libtestso.so)
libc.so.6 needed by .//libtestso.so
found libc.so.6 at /lib/i386-linux-gnu/libc.so.6
ld-linux.so.2 needed by /lib/i386-linux-gnu/libc.so.6
found ld-linux.so.2 at /lib/i386-linux-gnu/ld-linux.so.2
/usr/bin/ld.bfd.real: warning: cannot find entry symbol _start; not setting start address

Wednesday, November 4, 2015

Function Pointers in C/C++



#include <iostream>
#include <cstring>
#include <vector>

using namespace std;
namespace DemoFunPt {
typedef void (*CallBackFunc)(int i_input);
// Register callback function
vector<CallBackFunc> Callbackfuncs;

void Func_A(int i_input)
{
  cout<< "Hello from Func_A " << i_input << endl;
}

void Func_B(int i_input)
{
  cout<< "Hello from Func_B " << i_input << endl;
}

void RegisterCallbackFunc(CallBackFunc i_FuncPt)
{
  Callbackfuncs.push_back(i_FuncPt);
}

}

int  main()
{
   DemoFunPt::RegisterCallbackFunc(DemoFunPt::Func_A);
   DemoFunPt::RegisterCallbackFunc(DemoFunPt::Func_B);

   for(int i=0; i< DemoFunPt::Callbackfuncs.size(); i++){
      DemoFunPt::Callbackfuncs[i](i);
   }
   cout<<"Done demo" << endl;
   return 0;
}



root@trac ~# g++ funcpointer.cpp -o test
root@trac ~# ./test
Hello from Func_A 0
Hello from Func_B 1
Done demo

Wednesday, October 28, 2015

Static Variable Inside C Function.

#include <stdio.h>

#define TEST_3


void FuncA ()
{
#ifdef TEST_0
  // 0 value initialization only happen once if defined 'static'.
  static int StaticVar=0;
#endif
#ifdef TEST_1
  // 0 value initialization happen every time when FuncA is called.
  int StaticVar=0;
#endif
#ifdef TEST_2
  // When not give inital value, system set StaticVar to '0'
  // Changed value will stay next time when FuncA is called as StaticVar
  // is defined with keyward 'static'.
  static int StaticVar;
  printf("StaticVar is : %d\n",StaticVar);
  StaticVar = 2;
#endif
#ifdef TEST_3
  // When no 'static', system set StaticVar to a random value.
  // (I think it depends on what value in stack.)
  // But in test it seems, StaticVar keep same value as it's retrieving 
  // value from same postion in stack.
  int StaticVar;
  printf("StaticVar is : %d\n",StaticVar);
  StaticVar = 3;
#endif

  printf("StaticVar is : %d\n",StaticVar);
  StaticVar++;

}


void main()
{
  FuncA();
  FuncA();
  FuncA();
  FuncA();
  FuncA();
  FuncA();
  printf ("====Done====\n"); 

}
The results after defining different test cases:

Test_0
qyang@lubuntu-laptop:~$ ./Learn_static 
StaticVar is : 0
StaticVar is : 1
StaticVar is : 2
StaticVar is : 3
StaticVar is : 4
StaticVar is : 5
====Done====
Test_1
qyang@lubuntu-laptop:~$ ./Learn_static 
StaticVar is : 0
StaticVar is : 0
StaticVar is : 0
StaticVar is : 0
StaticVar is : 0
StaticVar is : 0
====Done====
Test_2
qyang@lubuntu-laptop:~$ ./Learn_static 
StaticVar is : 0
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
====Done====
Test_3
qyang@lubuntu-laptop:~$ ./Learn_static 
StaticVar is : 134513947
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
====Done====

Sunday, September 27, 2015

Install gcc / g++ man page manually on Debian.

[1] http://unix.stackexchange.com/questions/42474/find-and-install-man-file-manually


 Install gcc / g++ man page manually on Debian.

Edit /etc/apt/sources.list to include non-free repositories.

#apt-get update

#apt-get install gcc-doc

Wednesday, March 21, 2012

C Call C++

[1] ParaShift.com
     isocpp.org/wiki/faq/mixing-c-and-cpp
[2] Bytes.com
[3] research.att.com


From [3]
------------------------
 // C++ code:
 extern "C" void f(int);
 void f(int i){
  // ...
 }
 /* C code: */
 void f(int);
 void cc(int i){
  f(i);
  /* ... */
 }

// C++ code:
 class C {
  // ...
  virtual double f(int);
 };

 extern "C" double call_C_f(C* p, int i) // wrapper function
 {
  return p->f(i);
 }

 /* C code: */
 double call_C_f(struct C* p, int i);
 void ccc(struct C* p, int i){
  double d = call_C_f(p,i);
  /* ... */
 }


 // C++ code:
 void f(int);
 void f(double);

 extern "C" void f_i(int i) { f(i); }
 extern "C" void f_d(double d) { f(d); }

 /* C code: */
 void f_i(int);
 void f_d(double);

 void cccc(int i,double d){
  f_i(i);
  f_d(d);
  /* ... */
 }




From [1]
-----------------------------
main.cpp

// This is C++ code
#include "Fred.h"
int main()
{
  Fred fred;
  c_function(&fred);
} 



c-function.c

/* This is C code */
#include "Fred.h"

void c_function(Fred* fred){
   unsigned char lc;

   cplusplus_callback_function(fred);
   lc=Cplusplus_CallbackFunction_Wilma(456,fred);
   printf("return of C++ Wilma: %d\n",lc);
} 


Fred.cpp

// This is C++ code
#include "Fred.h"
#include  /*std::cout<<*/

//Fred::Fred() : a_(0) { }
Fred::Fred() { }

void Fred::wilma(int a) { std::cout<<"wilma(arg) print arg "<        

Fred* cplusplus_callback_function(Fred* fred){
  fred->wilma(123);
  return fred;
} 

//Provide access of C++ methods from C code.
unsigned char Cplusplus_CallbackFunction_Wilma(int a, Fred* fred){
  fred->wilma(a);
  return(0);
} 


Fred.h

 
/* This header can be read by both C and C++ compilers */
 #ifndef FRED_H
 #define FRED_H

 #ifdef __cplusplus
   class Fred {
   public:
     Fred();
     void wilma(int);
   private:
     int a_;
   };
 #else
   typedef struct Fred  Fred;

 #endif


 #ifdef __cplusplus
 extern "C" {
 #endif


 #if defined(__STDC__) || defined(__cplusplus)
   extern void c_function(Fred*);   /* ANSI C prototypes */
   extern Fred* cplusplus_callback_function(Fred*);
   extern unsigned char Cplusplus_CallbackFunction_Wilma(int a, Fred* fred);
 #else
   extern void c_function();        /* K&R style */
   extern Fred* cplusplus_callback_function();
 #endif

 #ifdef __cplusplus
 }

 #endif
 #endif /*FRED_H*/





Makefile
DESTDIR  = ./
PROGRAM = $(DESTDIR)/CCallCplusplus
SRCDIR = ./
INCL = -I ./
CP = g++
C = gcc
#C = arm-none-linux-gnueabi-g++

OBJS := $(addprefix $(DESTDIR)/,main.o Fred.o c-function.o)
DEBUG = -g
CFLAGS = -Wall $(DEBUG)

all:$(PROGRAM)

$(PROGRAM): $(OBJS)
 $(CP) -o $(PROGRAM) $(OBJS) -lpthread

$(DESTDIR)/%.o:$(SRCDIR)/%.cpp
 $(CP) -c $(CFLAGS) $< -o $@ $(INCL)

$(DESTDIR)/%.o:$(SRCDIR)/%.c
 $(C) -c $(CFLAGS) $< -o $@ $(INCL)

clean :
 rm -f $(OBJS)
 rm -f $(PROGRAM)



Result:

wilma(arg) print arg 123
wilma(arg) print arg 456
return of C++ Wilma: 0

Monday, February 28, 2011

Calling 'shell' from C/C++ code under Linux

See man page for those functions. Popen is better than system if want see return value of shell.

system()
popen()
pclose()

Sunday, January 23, 2011

Constant string shared accross classes.

In C++ using g++
------------------------
#ifdef THREAD_CLASS_CPP
const GSN_S8 *SPI_BUS_SYNCH="tA"; //0x7441;
#else
extern const GSN_S8 *SPI_BUS_SYNCH;
#endif


In C using gcc
---------------------
#ifndef DWIFI_C
extern const char ATI_REPLY_OK[];
#else
const char ATI_REPLY_OK[]="I/OK";
#endif

Monday, December 13, 2010

FW: 可重入函数

[1] http://blog.chinaunix.net/u2/68846/showart_689446.html


把一个不可重入函数变成可重入的唯一方法是用可重入规则来重写他。
其实很简单,只要遵守了几条很容易理解的规则,那么写出来的函数就是可重入的。

第一,不要使用全局变量。因为别的代码很可能覆盖这些变量值。
第二,在和硬件发生交互的时候,切记执行类似disinterrupt()之类的操作,就是关闭硬件中断。完成交互记得打开中断,在有些系列上,这叫做“进入/退出核心”或者用OS_ENTER_KERNAL/OS_EXIT_KERNAL来描述。
第三,不能调用任何不可重入的函数。
第四,谨慎使用堆栈。最好先在使用前先OS_ENTER_KERNAL。

还有一些规则,都是很好理解的,总之,时刻记住一句话:保证中断是安全的!

Wednesday, August 18, 2010

Static function in C

From: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/SYNTAX/static.htm


static functions are functions that are only visable to other functions in the same file. Consider the following code.

Wednesday, March 24, 2010

Static variable inside a function

int nonestatic_var_Test(void)
{
int number_of_times=0;

for(int y=0; y<10; y++)
{
number_of_times++;
}

return number_of_times;

}


int static_var_Test(void)
{
static int static_number_of_times = 0;

for(int y=0; y<10; y++)
{
static_number_of_times++;
}

return static_number_of_times;

}


int main()
{

int i;
int func_invoke_times;

for(i=0;i<10;i++)
func_invoke_times=static_var_Test();

printf("static_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=static_var_Test();
printf("static_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=nonestatic_var_Test();

printf("nonstatic_func_invoke_times is %d\n",func_invoke_times);

for(i=0;i<10;i++)
func_invoke_times=nonestatic_var_Test();
printf("nonstatic_func_invoke_times is %d\n",func_invoke_times);

}





result:

static_func_invoke_timers is 100
static_func_invoke_timers is 200
nonstatic_func_invoke_timers is 10
nonstatic_func_invoke_timers is 10

Sunday, August 16, 2009

String processing functions in C library

[1] http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

/* String functions in C library debugged in VC6 IDE

strncmp, strtol, strtok,strncpy,sprintf,atoi,

*/

#include "stdafx.h"
#include
#include //strncmp,strtok
#include //strtol

typedef unsigned char GSNTYPES_BYTE; /* 0 to 255 */
typedef char GSNTYPES_CHAR; /* -128 to 127 */


#define MAX_NUM_BYTES_HTML_TAG_VALUE (256) //limited by ConnectOne WiFi module.



int main()
{
//unsigned int len;

//len = strspn("this is a test","siht ");
//len = strspn("this is a test","se");
//printf("%d\n",len);


const char DASHSTRING[]="-";

const char CMD2TARGETREAD[]="Cmd2Target_Rd_\x31";
GSNTYPES_CHAR lcTagsValue[MAX_NUM_BYTES_HTML_TAG_VALUE];
GSNTYPES_BYTE lcTemp,lcWeb2TargetCmdCode;
char stringTemp[11];
char FakedMiMe_01[]="HTTP/1.1\xb7 200\xb7 OK\r\nServer:\xb7 CableTrackerIChip\r\nContent-Type:\xb7 application/octet-stream\r\n\r\n";
char word[]="\x6d=\x64=";



int i;


sprintf(lcTagsValue,"I/(-1)\r\n");
sprintf(stringTemp,"%s",strtok(lcTagsValue, "(:):\r\n"));
sprintf(stringTemp,"%s",strtok(NULL, "(:):\r\n"));
printf("decimal value of %s is %d \n", stringTemp,atoi(stringTemp));

sprintf(lcTagsValue,"I/(001)\r\n");
sprintf(stringTemp,"%s",strtok(lcTagsValue, "(:):\r\n"));
sprintf(stringTemp,"%s",strtok(NULL, "(:):\r\n"));
printf("decimal value of %s is %d \n", stringTemp,atoi(stringTemp));

sprintf(lcTagsValue,"I/(000)\r\n");
sprintf(stringTemp,"%s",strtok(lcTagsValue, "(:):\r\n"));
sprintf(stringTemp,"%s",strtok(NULL, "(:):\r\n"));
printf("decimal value of %s is %d \n", stringTemp,atoi(stringTemp));


printf (word);
printf(FakedMiMe_01);


// char string []="abc def ghi";
// char * word;


/* char num[15];

// Test a valid number
strcpy(num,"09012345");

printf("%s(Oct) is %i(Dec)\n", num, strtol(num, NULL, 8));
printf("%s(Dec) is %i(Dec)\n", num, strtol(num, NULL, 10));
printf("%s(hex) is %i(Dec)\n", num, strtol(num, NULL, 16));

puts("----------------------------------");

*/

printf("string is %s \n", CMD2TARGETREAD);


for (i=0;i {

printf("[%i]=%2X \n",i, CMD2TARGETREAD[i]);
}


sprintf(lcTagsValue,"I/(u got me)\r\nW");

sprintf(stringTemp,"%s",strtok(lcTagsValue, "(:):\r\n"));
printf("before bracket %s \n",stringTemp);

sprintf(stringTemp,"%s",strtok(NULL, "(:):\r\n"));
printf("in bracket %s \n",stringTemp);

sprintf(stringTemp,"%s",strtok(NULL, "(:):\r\n"));
printf("After CR/LR %s \n",stringTemp);
printf("After CR/LR 0x%02X \n",stringTemp[0]);

printf("len in bracket %u \n",strlen(stringTemp));


sprintf(lcTagsValue,"I/(u got me)\r\n");

sprintf(stringTemp,"%s",strtok(lcTagsValue, "(:):\r\n"));
printf("before bracket %s \n",stringTemp);

sprintf(stringTemp,"%s",strtok(NULL, "(:):\r\n"));
printf("in bracket %s \n",stringTemp);

sprintf(stringTemp,"%s",strtok(NULL, "(:):\r\n"));
printf("After CR/LR %s \n",stringTemp);
printf("After CR/LR 0x%02X \n",stringTemp[0]);

printf("len in bracket %u \n",strlen(stringTemp));



//sprintf(lcTagsValue,"Cmd2Target_Rd_0A");
sprintf(lcTagsValue,"11-22-33-AA-BB-CF");

printf("strlen(CMD2TARGETREAD) %d\n", strlen(CMD2TARGETREAD));


sprintf(stringTemp,"%s",strtok(lcTagsValue, DASHSTRING));
lcTemp=(GSNTYPES_BYTE)strtol(stringTemp,NULL,16);

printf("Mac Addr 1 %02x\n",lcTemp);

sprintf(stringTemp,"%s",strtok(NULL, DASHSTRING));
lcTemp=(GSNTYPES_BYTE)strtol(stringTemp,NULL,16);

printf("Mac Addr 2 %02x\n",lcTemp);


sprintf(stringTemp,"%s",strtok(NULL, DASHSTRING));
lcTemp=(GSNTYPES_BYTE)strtol(stringTemp,NULL,16);

printf("Mac Addr 3 %02x\n",lcTemp);

sprintf(stringTemp,"%s",strtok(NULL, DASHSTRING));
lcTemp=(GSNTYPES_BYTE)strtol(stringTemp,NULL,16);

printf("Mac Addr 4 %02x\n",lcTemp);

sprintf(stringTemp,"%s",strtok(NULL, DASHSTRING));
lcTemp=(GSNTYPES_BYTE)strtol(stringTemp,NULL,16);

printf("Mac Addr 5 %02x\n",lcTemp);

sprintf(stringTemp,"%s",strtok(NULL, DASHSTRING));
lcTemp=(GSNTYPES_BYTE)strtol(stringTemp,NULL,16);

printf("Mac Addr 6 %02X\n",lcTemp);


/* if (strncmp(CMD2TARGETREAD,lcTagsValue,strlen(CMD2TARGETREAD))==0)
{
//Read command -- 'Cmd2Target_Rd_4F'
//Change ASCII ('0' ~ 'F' )to HEX and refill the gcU2_RxBuffer[]

strncpy(stringTemp,&lcTagsValue[strlen(CMD2TARGETREAD)],2);

lcWeb2TargetCmdCode=(GSNTYPES_BYTE)strtol(stringTemp,NULL,16);



}
*/

printf("%d\n",lcWeb2TargetCmdCode);



/*
word=strtok(string, " ");

printf("%s\n",word);

//word=strtok(NULL, " ");
word=strtok(string, " ");

printf("%s\n",word);

*/

}

Wednesday, August 12, 2009

String operation in C/C++/Java -- strtok strspn

/* Copyright (c) 2001-2004 by SoftIntegration, Inc. All Rights Reserved */
/* a sample program that prints the index of the first
character in the string pointed to by str1 that does not
match any of the characters in str2.*/

#include "stdafx.h"
#include
#include

int main()
{
//unsigned int len;

//len = strspn("this is a test","siht ");
//len = strspn("this is a test","se");
//printf("%d\n",len);


char string []="abc def ghi";
char * word;

word=strtok(string, " ");

printf("%s\n",word);

//word=strtok(NULL, " ");
word=strtok(string, " ");

printf("%s\n",word);



}






/* STRSTR.C */

#include
#include

char str[] = "lazy";
char string[] = "The quick brown dog jumps over the lazy fox";
char fmt1[] = " 1 2 3 4 5";
char fmt2[] = "12345678901234567890123456789012345678901234567890";

void main( void )
{
char *pdest;
int result;
printf( "String to be searched:\n\t%s\n", string );
printf( "\t%s\n\t%s\n\n", fmt1, fmt2 );
pdest = strstr( string, str );
result = pdest - string + 1;
if( pdest != NULL )
printf( "%s found at position %d\n\n", str, result );
else
printf( "%s not found\n", str );
}


Output

String to be searched:
The quick brown dog jumps over the lazy fox
1 2 3 4 5
12345678901234567890123456789012345678901234567890

lazy found at position 36


String Manipulation Routines

See Also strcspn, strcmp, strpbrk, strrchr, strspn

Thursday, August 6, 2009

Tuesday, November 4, 2008

Structure to Structure copy

from :
http://forums.devx.com/archive/index.php/t-92711.html


why aren't you using plain assignment? C supports struct assignment:

struct A
{
int a;
float b;
char c;
long m;
};

struct A a;
struct A b;
b=a; /* works with ANSI C too*/

Danny
www.exontrol.com
10-09-2001, 05:52 PM
You can use memcpy(&a,&b, sizeof(yourstruct)), but if it contains strings,
or pointers, you have to copy individually that members,

Mike
www.exontrol.com