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

January 03, 2020

My first WebAssembly program

Hi folks,

Today, I am going to explain how to setup and write a sample program.

WebAssembly enables high performance applications on web pages. WebAssembly natively runs on browser along with HTML, CSS, JavaScript and approved by W3C (World Wide Web Consortium).

To know more about WebAssembly, go through the official webiste https://webassembly.org/

Pre-requisites


  1. Git
  2. CMake
  3. Host system compiler
    • Windows - Visual Studio 2017 +
    • Linux - GCC
    • Mac - XCode
  4. Python 2.7.x
After downloading and installing the pre-requisites, make sure git, cmake and python are accessible in path.

Install

  1. Open Terminal/PowerShell with Admin rights
  2. Get the emsdk files
    • git clone https://github.com/emscripten-core/emsdk.git
  3. Navigate to the downloaded folder emsdk
    • cd emsdk
  4. Install (Note: On PowerShell execute this command, Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine)
    • ./emsdk install latest
  5. Activate
    • ./emsdk activate latest

Create Sample HTML file

  • Create folder
    • mkdir hello
  • Navigate to the folder
    • cd hello
  • Create a file hello.c and place the following code
#include
int main(int argc, char ** argv) { printf("Hello PSR!\n");}

Convert C file to HTML

emcc hello.c -o hello.html

Run WebServer (Optional)

Run emrun webserver to serve the html pages.
emrun --no_browser --port 8080 .
Hope, the tutorial is useful. Happy coding.

Please send your comments and feedback to psrdotcom@gmail.com



April 29, 2012

Huffman Code in C/C++ with String as Node

Hi everyone,

I have copied someone's code and modified. But Since, the author has put the code as open source, I have done that for my friend.

Here it goes, Huffman code in C/C++

Source Code:
#include<conio.h>
#include<string.h>
#include<math.h>
#include<iostream.h>
#include<stdlib.h>

#define ARRAY_SIZE 20
#define MAX_NAME_LEN 25

int g,h,p,y,n;
char m[ARRAY_SIZE],b[ARRAY_SIZE][2],re;

int alpha = 65;

char name[ARRAY_SIZE][MAX_NAME_LEN];
int i=0,j=0,k=0;

/*
Perfoming operations
*/

//Tree Structure
struct tree
{
char a[20];
int s;
struct tree *left,*right;
}*root=NULL,*tt[20]={NULL},*temp,*temp2,*t2,*ri,*le;


// Queur Structure
struct pqu
{
int info;
char a[20];
struct pqu *ptr;
}*front=NULL,*t,*par,*t1,*p1,*p2;

// Pointer to queue
struct pqu* fp(int info)
{
struct pqu *p=NULL;
for(t1=front;t1->info<info&&t1!=NULL;t1=t1->ptr)
{
p=t1;
}
return (p);

}

//PUSH operation
void enqu(char a[20],int p)
{
t=(struct pqu*)malloc(sizeof(struct pqu));
strcpy(t->a,a);
t->info=p;
t->ptr=NULL;
if(front==NULL)
{
front=t;
}
else
{
par=fp(p);
if(par==NULL)
{
t->ptr=front;
front=t;
}
else
{
t->ptr=par->ptr;
par->ptr=t;
}
}
}

// POP operation
struct pqu* dequ()
{
t1=front;
front=front->ptr;
return t1;
}

//Get Info of a leaf
void info(char c[2])
{
int m=0,i;
temp2=root;
while(strcmp(c,temp2->a)!=0)
{
t2=temp2->left;
for(i=0;i<strlen(t2->a);i++)
{
if(t2->a[i]==c[0])
{
temp2=temp2->left;
m=1;
cout<<”0&”;
break;
}
}
if(m!=1)
{
temp2=temp2->right;
cout<<&”1&”;
}
m=0;
}
}

// Insert Operation
void insert()
{
char a1[20],b1[20],v1[20];
int i,j,z=0,l;
while(front!=NULL)
{
p1=dequ();
strcpy(a1,p1->a);
l=p1->info;
p2=dequ();
if(p2==NULL)
break;
strcpy(b1,p2->a);
strcpy(v1,a1);
temp=(struct tree*)malloc(sizeof(struct tree));
strcpy(temp->a,strcat(v1,b1));
temp->s=l+p2->info;
temp->left=NULL;
temp->right=NULL;
temp2=temp;
root=temp;
for(i=0;i<z;)
{
if(strcmp(tt[i]->a,a1)==0)
{
temp->left=tt[i];
for(l=i;l<z;l++)
{
tt[l]=tt[l+1];
}
i=0;
continue;
}
else if(strcmp(tt[i]->a,b1)==0)
{
temp->right=tt[i];
for(l=i;l<z;l++)
{
tt[l]=tt[l+1];
}
i=0;
continue;
}
i++;
}
if(temp->left==NULL)
{
le=(struct tree*)malloc(sizeof(struct tree));
strcpy(le->a,a1);
le->left=NULL;
le->right=NULL;
temp2->left=le;
}
if(temp->right==NULL)
{
ri=(struct tree*)malloc(sizeof(struct tree));
strcpy(ri->a,b1);
ri->left=NULL;
ri->right=NULL;
temp2->right=ri;
}
if(front!=NULL)
enqu(temp2->a,temp2->s);
tt[z++]=temp2;
}
}

//Display Tree
void disp(struct tree *rt)
{
if(rt!=NULL)
{
disp(rt->left);
//cout<<””<<rt->a;disp(rt->right);
}
}

//Display Name
void displayname(int idx)
{
cout<<name[idx]<<”: ”;
}

/*
End of operations
*/


//Main Method

int main()
{
while(1)
{
//Clear Screen
clrscr();

cout<<”Enter the total no of leafs : ”;
cin>>n;


for(i=0;i<n;i++,alpha++)
{
cout<<”Enter Name: ”;
cin>>name[i];

//itoa(alpha,m,10);
//strcpy(m,(char*)alpha[i]);
*m=(char)alpha; //Assigning Local Values
strcpy(b[i],m);

cout<<”Enter frequency for ”<<name[i]<<” : ”;
cin>>g;

//Enque to the list
enqu(m,g);

} //Repeat till all the leafs data entered

insert(); // Form the tree
disp(root); // Display the codeword of leaf from root


for(i=0;i<n;i++)
{
displayname(i);
info(b[i]);
cout<<”n”;
}

cout<<”nDo You Want To Continue Y or N: ”;
cin>>re;
clrscr();
if(re=='y'||re=='Y')
continue;
else
break; //exit(0);
}

return 0;
}//end of while

Output:

I am also making this as an open source code. Anyone can edit, share, re-distribute the code.

For further queries, please mail to psrdotcom@gmail.com

December 30, 2011

Android NDK JNI Windows xp/7 with 32/64 bit Installation Problems with Solutions in Eclipse without C/C++ CDT Plugin

Hi all,

I spent 2 days on configuring this. I read lot of blogs and instrutction steps from various sites. I would like share my experience on installing Android NDK and Working with Eclipse.

Objective:
Using JNI Technology in Eclipse with Android NDK r6/r7 on Windows xp/7 Professional

Pre-requirements:
  1. Java SE SDK -- Java Development Kit
  2. Eclipse Helios/Indigo -- IDE to work with Java, Android, C/C++ etc.
  3. Android SDK -- Android Applications Development Kit
  4. Android ADT Plugin for Eclipse -- Download the latest Android SDK Platform Tools
  5. C/C++ Plugin for Eclipse (Optional) -- Make sure that .c, .cpp, .h files opening from Eclipse
  6. Android NDK (r6/r7) -- Native development i.e. Running c libraries in Android
  7. Cygwin 1.7.x or above -- Makefile creation, Library file creation tools, Compiling C files

Installation:
  1. Install the Java Development Kit
  2. Install the Android SDK and ADT Plugin with Eclipse
  3. [Optional] Install CDT plugin for Eclipse
  4. Download and extract the Android NDK
  5. Install Cygwin 1.7.x or above
Note: Don't extract in a folder where folder name is having spaces in between words.
Example:
"Program Files" -- Don't Use
"ProgramFiles" -- Use

Configuration:
Please make sure that you have set the environment variables like
  • JAVA_HOME -- Java Home Directory
  • NDK_HOME -- Android NDK Home Directory
  • Update Path Variable with JDK Bin folder
Creating Android Application
  • In Eclipse, Select File->New->Android Project
  • Enter the Project Name and Click on "Next" button
  • Select the "Build Target", I opted for Android 2.2, SDK 8 Version and Click on "Next" button
  • In Application Info dialog, enter the "Package Name" and Select "Finish" button
  • Now, you can see the newly created SampleNDK project in the eclipse project explorer window

Example:
  • Eclipse Workspace Folder: D:\Workspace
  • Android Application Name: SampleNDK
  • Android Application Working Folder: D:\Workspace\SampleNDK
  • Package Name: com.samplendk
  • Android Application Source Folder: D:\Workspace\SampleNDK\src

Source of AndroidNDKActivity.java
package com.samplendk;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class SampleNDKActivity extends Activity {
   
    //Declare the native method
    private native String invokeNativeFunction();
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //Call the native methods
        String hello = invokeNativeFunction();
        new AlertDialog.Builder(this).setMessage(hello).show();
    }
   
}

  • Create a folder named "jni" in the project
    • Right click on the "SampleNDK" project-> Select "New"-> Select "Folder"->Type "jni"
  • Create files "Android.mk" and "native.c" in Jni folder
    • Right click on the "jni" folder-> Select "New"-> Select "File"->Type "Android.mk"
    • Right click on the "jni" folder-> Select "New"-> Select "File"->Type "native.c"
  • After Creating those folder and files, the project explorer window look like this
  • Do some continuous steps.
    • Build, Refresh, and Clean project
      • Right Click on the "SampleNDK" project and Select the "Build Project"
      • Select "Sample NDK" project and Click "F5" button on keyboard
      • Select "Project" menu and Select "Clean" option

  • Create header file of the java file
    • In windows command prompt, change to project source directory
    • Syntax:
      • cmd>
      • cmd> cd ProjectDir/src

    • Example:
      • cmd> D:
      • D:\> cd SampleNDK/src
    • Run the Javah command to create header file
    • Syntax:
      • cmd> javah -jni .javafile_without_.java_extension // JDK 1.7
      • cmd> javah -classpath ..\bin\classes .javafile_without_.java_extension //JDK1.6
    • Example:
      • D:\SampleNDK\src> javah -jni com.samplendk.SampleNDKActivity //JDK1.7
      • D:\SampleNDK\src> javah -classpath ..\bin\classes com.samplendk.SampleNDKActivity //JDK1.6
    • Note:
      • Don't include the .java at the end of javah command

  • Copy the created java header file to jni folder
    • D:\SampleNDK\src> copy com_samplendk_SampleNDKActivity.h ..\jni

  • Go to Eclipse and Refresh the project by pressing "F5" on keyboard.
  • Open the header file from jni folder
  • Copy the function created by javah as shown below
  • Paste the code in native.c and change the code similar to this
Source of native.c
#include <string.h>
#include "com_samplendk_SampleNDKActivity.h"

jstring JNICALL Java_com_samplendk_SampleNDKActivity_invokeNativeFunction
  (JNIEnv *env, jobject obj)
{
    return (*env)->NewStringUTF(env, "Hello from native function !!");
}

Source of Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Here we give our module name and source file(s)
LOCAL_MODULE := SampleNDK
LOCAL_SRC_FILES := native.c

include $(BUILD_SHARED_LIBRARY)

  • Run Cygwin.bat file in the Cygwin installed directory
  • It will open the cygwin command prompt
  • Change the directory to SampleNDK project directory
    • Note: All the drives in your systems are mounted to some directory in the cygwin.
    • To see your drive mount points type mount
    • # mount
  • # cd /cygdrive/d/SampleNDK/
  • Run the ndk-build command from the android ndk directory
    • # /cygdrive/d/android-ndk-r7/ndk-build

  • Error(Only in Android-ndk-r7):
  • You may get some error like the following
    • /awk.exe: can't open file check-awk.awk
    • Andoid NDK: Host 'awk' tool is outdated. Please define
    • HOST-Awk to Point to Gawk or Nawk !
  • Resolution:
    • Goto the android-ndk/prebuilt/windows/bin/
    • Change the awk.exe to awk_.exe

  • Now you may see the following output after successful execution
  • After successful creating libSampleNDK.so file, refresh your Eclipse project
  • You can see the updated "Project Explorer" with "libs" folder in the tree hierarchy
  • Update the java source code now by adding this library to it
Source code of SampleNDKActivity.java
package com.samplendk;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class SampleNDKActivity extends Activity {
   
    static
    {
        System.loadLibrary("SampleNDK");
    }

   
    //Declare the native method
    private native String invokeNativeFunction();
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //Call the native methods
        String hello = invokeNativeFunction();
        new AlertDialog.Builder(this).setMessage(hello).show();
    }
   
}

  • Clean the project by Selecting "Project"->"Clean"
  • Run the application as "Android Application"
  • Note:
    • Error:
      • java.lang.unsatisfiedLinkError Library -- not found
    • Resolution:
      • Please see if you have added the "lib" in java source before adding the library in System.loadLibrary() method
  • Please find the screenshot of above running program in emulator


If you have queries, please mail to psrdotcom@gmail.com

Eclipse C C++ CDT Plugin Download and Installation with Link or Location Problem Solution

Hi all,

If you are using Eclipse with Java or any other platform and you are planning to install the C/C++(CDT) Plugin then please follow the steps.

Installation Steps:
  • In Eclipse, Click the Help->"Install New Software"
  • You will get a Install named window
  • Click "Add" button
  • Please remove the dot(.) at the end while adding the CDT Plugin location from the link.
  • In "Install" Window, "Work with" textbox, please type the CDT and you will prompted with different options, Select the desired option and click/hit "Enter/Return" button.
  • It will show the similar kind of screen as shown below
  • You can select the all/desired tools to download
  • Please "Restart Eclipse" to complete the CDT Plugin installation for Eclipse
  • Now you can develop your C/C++ applications with Eclipse

Happy Coding ..


For further queries, please mail to psrdotcom@gmail.com

December 27, 2011

Java Native Interface (JNI) in Netbeans with C/C++ and Java Hello World Sample Source Code

Hi all,

Today I configured the Netbeans IDE to work with Java Native Interface (JNI).

Pre-Requisites:
  1. Java Development Kit (JDK)
  2. Cygwin (or) MinGW & MSYS
  3. NetBeans IDE with Java and C/C++ Bundle

Installation:
  • Install JDK
  • Install Cygwin (or) MinGW&MSYS
  • Note: While installing please choose the destination directory name without spaces
  • I have installed NetBeans IDE All Version, because I thought, I will need all the technologies. That is different approach.

Configuration:
  • Set the environment variables like JAVA_HOME and PATH with Java Installation Directory and JDK bin, Cygwin/MinGW&MSYS bin directories respectively
  • Cygwin/MinGW integration with NetBeans
  • Configure the C/C++ with Tools MinGW bin directory, which automatically fills the corresponding compilers

Source Code:

  • Create a sample java application with the following detail

package javaapp1.JavaApp1;

public class JavaApp1
{
public static void main(String [] args)
{
  new JavaApp1.nativePrint();
}

private native void nativePrint();
}

  • Clean and Build the java project
  • In Command Prompt, Navigate to Netbeans Project Directory
    • cmd> cd Netbeans/ProjectDir
  • Create the Java header file
    • cmd> javah -o JavaApp1.h -classpath JavaApp1\build\classes javaapp1.JavaApp1

  • Create a C/C++ Dynamic Library Project in Netbeans (In this example, it is CppDll1)
  • Change some of the project properties
  • Make sure that, you have downloaded and configured the proper Cygwin/MinGW with exact Architecture 32bit/64bit
  •  Make sure that you are using proper gcc for 32bit/64bit dll creation
  • Linker must be of same architecture, 32bit/64bit


  • Include the Java header file, which we have created in Java Project.
    • Right click on the "Source Files"-> Select "Add an Existing Item"
    • Select the created header file from Project Home Directory
    • (OR)
    • Manually copy the created header file from Project home directory to CppDll directory
  • Create a C Source file in "Source Files" in CppDll1 project
 #include "JavaApp1.h"

JNIEXPORT void JNICALL Java_javaapp1_JavaApp1_nativePrint(JNIEnv *env, jobject obj)
{
    printf("\nHello World from C\n");  
}
  • Clean and Build the C code. I have faced the following issue.
    • Issues Faced:
      • I am using Windows 7 64-bit and installed Jdk 64-bit. But initially I have installed MinGW 32 bit and it is generating only 32 bit DLL which is not suitable to run the Java application in NetBeans.
    • Resolution:
      • Downloaded MinGW 64 bit and configured in the NetBeans C/C++ Options
  • Copy the .dll file path
  • In Java project, open the main class and add the following content
package javaapp1.JavaApp1;

public class JavaApp1
{
static
{
  System.load("dll file path");
}
public static void main(String [] args)
{
  new JavaApp1.nativePrint();
}

private native void nativePrint();
}
  • Clean and Build the project
  • Run the Java project to see the final JNI output.

References:
http://java.sun.com/docs/books/jni/html/jniTOC.html
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html
http://www.cygwin.com/
http://sourceforge.net/projects/mingw-w64/
http://netbeans.org/community/releases/71/install.html

Please send your feedback to psrdotcom@gmail.com

August 08, 2008

Linux C Code Debugging for Segmentation Fault with GDB

Hi Friends,

Whenever you are doing some programming, you will be getting lot of errors. Myself have been in the same situation while programming.

When I was tried to write a code in C language (though I'm not a good programmer of C language), For my friend's sake I have tried some code.

The most frustrating error came in to picture, called "Segmentation Fault". Took help of google and no clue why I was getting the error.

What I have understand about Segmentation fault is
"Segmentation fault appears as if it is not easy to understand;
when your trying to access the memory that is not allocated by you ...
then segmentation fault appears after executing a.out"

Let me explain you with an example

int a[5]; // Declare an array
printf("%d\n",a[6]); // Then try to print the last+n location of the array where n>0

You will get segmentation fault error.


How to over come this?

There are different debuggers to locate the memory area where the segmentation fault occurred.

Procedure:
  1. 1.c // Your file name
  2. gcc 1.c -g // Then compile it
  3. gdb a.out // Type at the command prompt/console
  4. Now you will get a prompt >>>
  5. Type 'r'
  6. Give the required input
  7. It will locate the memory area where your trying to access the memory
  8. u is not allocate by u (it will give the lines in the program 1.c here segmentation fault has occurred )

You can rely on gdb about 70% and there are also other debuggers
for which you can refer to the book "Linux is a Nutshell"

For further queries/comments mail to psrdotcom@gmail.com

Featured Post

Java Introdcution

Please send your review and feedback to psrdotcom@gmail.com