​
Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Saturday, 29 July 2017

Create static library for C program in Linux

Create static library for C program in Linux


Consider your C program has three files, which are addSub.c, mulDiv.c and main.c

addSub.c : 
int add(int x, int y)
{
    return x + y;
}
 
int sub(int x, int y)
{
        return x - y;
}
mulDiv.c : 
int mul(int x, int y)
{
    return x * y;
}
 
int div(int x, int y)
{
        return x / y;
}
main.c : 
#include <stdio.h>
 
int main(int argc, char *argv[])
{
    printf("%d ", add(10, 15));
    printf("%d ", sub(50, 15));
    printf("%d ", add(10, 3));
    printf("%d ", add(100, 4));
    return 0;
}

1 . Compile and create object file for addSub.c and mulDiv.c 
gcc -c addSub.c mulDiv.c -Wall
2.  Create static library( liboperation.a ) for compiled files 
ar -cvq libopeartion.a addSub.o mulDiv.o
3.  We can list the available files from library file using following
ar -t libopeartion.a
4. Compile the main program with linking the library 
gcc -o output main.c libopeartion.a
5. Run the created output executable file
./output 

{ Read More }


Friday, 21 July 2017

Create a comma separated string in shell a b c a b c no not sed

Create a comma separated string in shell a b c a b c no not sed


Well, the title does not really explain the real issue but I couldnt find a better one.

Another try: assume you have a list of tokens in a shell script and you want to build a comma separated list out of those tokens and you want to do this in a loop there is usually an issue with one comma too many at the beginning or at the end.

For simplicity I use a simple token list.
This example of course could be solved faster with sed.
I add a more complex example at the end.

A first approach is as follows and will create a list with an empty first element so to speak:
TOKENS="a b c" LIST="(" for token in $TOKENS ; do LIST="${LIST},${token}" done LIST="${LIST})" echo $LIST (,a,b,c) 
So how does one get rid of the extra empty element at the beginning of the list?

One might add an if-statement:
TOKENS="a b c" LIST="(" for token in $TOKENS ; do if [ "x$LIST" = "x(" ] ; then LIST="${LIST}${token}" else LIST="${LIST},${token}" fi done LIST="${LIST})" echo $LIST (a,b,c) 
In my search for a shorter one line solution I found the following approach using shell paremeter substitution.
TOKENS="a b c" LIST="" for token in $TOKENS ; do LIST="${LIST:-(}${LIST:+,}${token}" done LIST="${LIST})" echo $LIST (a,b,c) 
This is admittedly not easy to understand on the first glance unless you are very familiar with the parameter substitution.
Im using the complementary idea of :- and :+ .
${LIST:-(} will put out either the current value of LIST (if it exists and is not empty) or a ( .
So in the first invocation of the loop LIST is not yet set and thus ( is put out.
In the next rounds LIST is set and will be put out as is.
${LIST:+,} will put out either a comma (if LIST exists and is set) or nothing at all.
In the first invocation of the loop LIST is not yet set and nothing is put out.
In the next rounds LIST is set and a comma will be put out.

In all cases the token is appended at the end.

Here is a an example with more complex tokens which contain a space and they should be surrounded by quotes in the resulting list.
A="sam smith" B="jane jones" C="gabe miller" LIST="" for token in "$A" "$B" "$C" ; do LIST="${LIST:-(}${LIST:+,}${token}" done LIST="${LIST})" echo $LIST (sam smith,jane jones,gabe miller) 
{ Read More }


Thursday, 20 July 2017

Converting Ekam to C 0x

Converting Ekam to C 0x


I converted Ekam to C++0x. As always, all code is at:

http://code.google.com/p/ekam/

Note that Ekam now requires a C++0x compiler. Namely, it needs GCC 4.6, which is not officially released yet. I didnt have much trouble compiling and using the latest snapshot, but I realize that it is probably more work than most people want to do. Hopefully 4.6 will be officially released soon.

Introduction

When writing Ekam, with no company style guide to stop me, I have found myself developing a very specific and unique style of C++ programming with a heavy reliance on RAII. Some features of this style:

  • I never use operator new directly (much less malloc()), but instead use a wrapper which initializes an OwnedPtr. This class is like scoped_ptr in that it wraps a pointer and automatically deletes it when the OwnedPtr is destroyed. However, unlike scope_ptr, there is no way to release a pointer from an OwnedPtr except by transferring it to another OwnedPtr. Thus, the only way that an object pointed to by an OwnedPtr could ever be leaked (i.e. become unreachable without being reclaimed) is if you constructed an OwnedPtr cycle. This is actually quite hard to do by accident -- much harder than creating a cycle of regular pointers.
  • Ekam is heavily event-driven. Any function call which starts an asynchronous operation returns an OwnedPtr<AsyncOperation>. Deleting this object cancels the operation.
  • All OS handles (e.g. file descriptors) are wrapped in objects that automatically close them.

These features turn out to work extremely well together.

A common problem in multi-tasking C++ code (whether based on threads or events) is that cancellation is very difficult. Typically, an asynchronous operation calls some callback at some future time, and the caller is expected to ensure that the callbacks context is still valid at the time that it is called. If youre lucky, the operation can be canceled by calling some separate cancel() function. However, its often the case that this function simply causes the callback to complete sooner, because its considered too easy to leak memory if an expected callback is never called. So, you still have to wait for the callback.

So what happens if you really just want to kill off an entire large, complex chunk of your program all at once? It turns out this is something I need to do in Ekam. If a build action is in progress and one of its inputs changes, the action should be immediately halted. But actions can involve arbitrary code that can get fairly complex. What can Ekam do about it?

Well, with the style Ive been using, cancellation is actually quite easy. Because all allocated objects must be anchored to another object via an OwnedPtr, if you delete a high-level object, you can be pretty sure that all the objects underneath will be cleanly deleted. And because asychronous operations are themselves represented using objects, and deleting those objects cancel the corresponding operations, its nearly impossible to accidentally leave an operation running after its context has been deleted.

Problem: OwnedPtr transferral

So what does this have to do with C++0x? Well, there are some parts of my style that turn out to be a bit awkward.

Transferring an OwnedPtr to another OwnedPtr looked like this:

 OwnedPtr<MyObject> ptr1, ptr2; //... ptr1.adopt(&ptr2); 

Looks fine, but this means that the way to pass ownership into a function call is by passing a pointer to an OwnedPtr, getting a little weird:

 void Foo::takeOwnership(OwnedPtr<Bar>* barToAdopt) { this->bar.adopt(barToAdopt); } ... Foo foo; OwnedPtr<Bar> bar; ... foo.takeOwnership(&bar); 

Returning an OwnedPtr is even more awkward:

 void Foo::releaseOwnership(OwnedPtr<Bar>* output) { output->adopt(&this->bar); } ... OwnedPtr<Bar> bar; foo.releaseOwnership(&bar); bar->doSomething(); 

Furthermore, the way to allocate an owned object was through a method of OwnedPtr itself, which was kind of weird to call:

 OwnedPtr<Bar> bar; bar.allocate(constructorParam1, constructorParam2); foo.takeOwnership(&bar); 

This turned out to be particularly ugly when allocating a subclass:

 OwnedPtr<BarSub> barSub; barSub.allocate(constructorParam1, constructorParam2); OwnedPtr<Bar> bar; bar.adopt(&barSub); foo.takeOwnership(&bar); 

So I made a shortcut for that:

 OwnedPtr<Bar> bar; bar.allocateSubclass<BarSub>( constructorParam1, constructorParam2); foo.takeOwnership(&bar); 

Still, dealing with OwnedPtrs remained difficult. They just didnt flow right with the rest of the language.

Rvalue references

This is all solved by C++0xs new "rvalue references" feature. When a function takes an "rvalue reference" as a parameter, it only accepts references to values which are safe to clobber, either because the value is an unnamed temporary (which will be destroyed immediately when the function returns) or because the caller has explicitly indicated that its OK to clobber the value.

Most of the literature on rvalue references talks about how they can be used to avoid unnecessary copies and to implement "perfect forwarding". These are nice, but what I really want is to implement a type that can only be moved, not copied. OwnedPtrs explicitly prohibit copying, since this would lead to double-deletion. However, moving an OwnedPtr is perfectly safe. By implementing move semantics using rvalue references, I was able to make it possible to pass OwnedPtrs around using natural syntax, without any risk of unexpected ownership stealing (as with the old auto_ptr).

Now the code samples look like this:

 // Transferring ownership. OwnedPtr<MyObject> ptr1, ptr2; ... ptr1 = ptr2.release(); // Passing ownership to a method. void Foo::takeOwnership(OwnedPtr<Bar> bar) { this->bar = bar.release(); } ... Foo foo; OwnedPtr<Bar> bar; ... foo.takeOwnership(bar.release()); // Returning ownership from a method. OwnedPtr<Bar> Foo::releaseOwnership() { return this->bar.release(); } ... OwnedPtr<Bar> bar = foo.releaseOwnership(); bar->doSomething(); // Allocating an object. OwnedPtr<Bar> bar = newOwned<Bar>( constructorParam1, constructorParam2); // Allocating a subclass. OwnedPtr<Bar> bar = newOwned<BarSub>( constructorParam1, constructorParam2); 

So much nicer! Notice that the release() method is always used in contexts where ownership is being transfered away from a named OwnedPtr. This makes it very clear what is going on and avoids accidents. Notice also that release() is NOT needed if the OwnedPtr is an unnamed temporary, which allows complex expressions to be written relatively naturally.

Problem: Callbacks

While working better than typical callback-based systems, my style for asynchronous operations in Ekam was still fundamentally based on callbacks. This typically involved a lot of boilerplate. For example, here is some code to implement an asynchronous read, based on the EventManager interface which provides asynchronous notification of readability:

 class ReadCallback { public: virtual ~ReadCallback(); virtual void done(size_t actual); virtual void error(int number); }; OwnedPtr<AsyncOperation> readAsync( EventManager* eventManager, int fd, void* buffer, size_t size, ReadCallback* callback) { class ReadOperation: public EventManager::IoCallback, public AsyncOperation { public: ReadOperation(int fd, void* buffer, size_t size, ReadCallback* callback) : fd(fd), buffer(buffer), size(size), callback(callback) {} ~ReadOperation() {} OwnedPtr<AsyncOperation> inner; // implements IoCallback virtual void ready() { ssize_t n = read(fd, buffer, size); if (n < 0) { callback->error(errno); } else { callback->done(n); } } private: int fd; void* buffer; size_t size; ReadCallback* callback; } OwnedPtr<ReadOperation> result = newOwned<ReadOperation>( fd, buffer, size, callback); result.inner = eventManager->onReadable(fd, result.get()); return result.release(); } 

Thats a lot of code to do something pretty trivial. Additionally, the fact that callbacks transfer control from lower-level objects to higher-level ones causes some problems:

  • Exceptions cant be used, because they would propagate in the wrong direction.
  • When the callback returns, the calling object may have been destroyed. Detecting this situation is hard, and delaying destruction if needed is harder. Most callback callers are lucky enough not to have anything else to do after the call, but this isnt always the case.

C++0x introduces lambdas. Using them, I implemented E-style promises. Heres what the new code looks like:

 Promise<size_t> readAsync( EventManager* eventManager, int fd, void* buffer, size_t size) { return eventManager->when(eventManager->onReadable(fd))( [=](Void) -> size_t { ssize_t n = read(fd, buffer, size); if (n < 0) { throw OsError("read", errno); } else { return n; } }); } 

Isnt that pretty? It does all the same things as the previous code sample, but with so much less code. Heres another example which calls the above:

 Promise<size_t> readPromise = readAsync( eventManager, fd, buffer, size); Promise<void> pendingOp = eventManager->when(readPromise)( [=](size_t actual) { // Copy to stdout. write(STDOUT_FILENO, buffer, actual); }, [](MaybeException error) { try { // Force exception to be rethrown. error.get(); } catch (const OsError& e) { fprintf(stderr, "%s ", e.what()); } }) 

Some points:

  • The return value of when() is another promise, for the result of the lambda.
  • The lambda can return another promise instead of a value. In this case the new promise will replace the old one.
  • You can pass multiple promises to when(). The lambda will be called when all have completed.
  • If you give two lambdas to when(), the second one is called in case of exceptions. Otherwise, exceptions simply propagate to the lambda returned by when().
  • Promise callbacks are never executed synchronously; they always go through an event queue. Therefore, the body of a promise callback can delete objcets without worrying that they are in use up the stack.
  • when() takes ownership of all of its arguments (using rvalue reference "move" semantics). You can actually pass things other than promises to it; they will simply be passed through to the callback. This is useful for making sure state required by the callback is not destroyed in the meantime.
  • If you destroy a promise without passing it to when(), whatever asynchronous operation it was bound to is canceled. Even if the promise was already fulfilled and the callback is simply sitting on the event queue, it will be removed and will never be called.

Having refactored all of my code to use promises, I do find them quite a bit easier to use. For example, it turns out that much of the complication in using Linuxs inotify interface, which I whined about a few months ago, completely went away when I started using promises, because I didnt need to worry about callbacks interfering with each other.

Conclusion

C++ is still a horribly over-complicated language, and C++0x only makes that worse. The implementation of promises is a ridiculous mess of template magic that is pretty inscrutable. However, for those who deeply understand C++, C++0x provides some very powerful features. Im pretty happy with the results.

{ Read More }


Tuesday, 18 July 2017

Create Matrix Effect in CMD BY a simple C program

Create Matrix Effect in CMD BY a simple C program


Creating Matrix Effect in CMD by a Simple C Program:




          Guys today Im providing you a simple .exe file which can create Matrix effect in CMD(Win32bit OS only).
  
So Download this .exe file from here

This is a sample for checking purpose.

And this is the source code for changing name in place of my name.

Download source code from here.

Open this .C file with TurboC Compiler and modify it and then click on compile button.

Modify only Name as in this program as I write ******Khattak******.

Now click on Compile Button and this time click on make option.It will create  *.exe file (i.e. ktk.exe).

So if you like my post then share it with friends and everyone.


{ Read More }


Sunday, 25 June 2017

CppUnit C port of JUnit Free Download

CppUnit C port of JUnit Free Download


CppUnit is the C++ port of the famous JUnit framework for unit testing.
CppUnit is a C++ unit testing framework. CppUnit project started its life as a port of JUnit to C++ by Michael Feathers.

Here are some key features of "CppUnit C++ port of JUnit":


� XML output with hooks for additional data
� Compiler-like text output to integrate with an IDE
� Helper macros for easier test suite declaration
� Hierarchical test fixture support
� Test registry to reduce recompilation need
� Test plug-in for faster compile/test cycle (self testable dynamic library)
� Protector to encapsulate test execution (allow capture of exception not derived from std::exception)
� MfcTestRunner
� QT based graphic test runner

Products homepage
Here are some key features of "CppUnit - C++ port of JUnit":

� XML output with hooks for additional data
� Compiler-like text output to integrate with an IDE
� Helper macros for easier test suite declaration
� Hierarchical test fixture support
� Test registry to reduce recompilation need
� Test plug-in for faster compile/test cycle (self testable dynamic library)
� Protector to encapsulate test execution (allow capture of exception not derived from std::exception)
� MfcTestRunner
� QT based graphic test runner

Click Here to Download

Sources mirror 1 (tar.gz)
{ Read More }


Tuesday, 20 June 2017

CONVERT STRING TO INTEGER OBJECTIVE C by Little

CONVERT STRING TO INTEGER OBJECTIVE C by Little


Name:String To Integer Objective C Converter
File size:25 MB
Date added:November 20, 2013
Price:Free
Operating system:Windows XP/Vista/7/8
Total downloads:1046
Downloads last week:87
Product ranking:★★★★★










She was advised by him to come back at once. Could you tell me the way? I wonder who started that rumor. I wish I had been there with you. Take anything you want. When is the next flight to Delhi? He really likes traveling a lot. I want an MP3 player! You are in favour of ... arent you? Will she get well soon?
String To Integer Objective C Converter: - My mother asked me not to feed the dog until after we had all eaten.
- I have one brother.
- I have to go to the police station.
- I have a cold now.
- Something must have happened to him on the way.
- There was a light rain yesterday.
- Oh, really? Thank you. That would help a lot.
- What is Ken eating?
- They might be taller than you.
- CONVERT STRING TO INTEGER OBJECTIVE C
- Lets take a trip.
She bit him. Could you draw a map for me? She devoted herself to him. How is your dad? Did you have a fight with Ken? That is an old camera. Dont throw garbage away here. Can I have your number please? She handed him a book. Show me how to do it, please.






String To Integer Objective C Converter charts






String To Integer Objective C Converter location




String To Integer Objective C Converter google search
String To Integer Objective C Converter ask google support
String To Integer Objective C Converter chrome extensions
String To Integer Objective C Converter for android
String To Integer Objective C Converter videos
String To Integer Objective C Converter twitter search
String To Integer Objective C Converter wiki
String To Integer Objective C Converter photos


String To Integer Objective C Converter world






String To Integer Objective C Converter youtube videos






String To Integer Objective C Converter bing photo search




String To Integer Objective C Converter, Inc. 80176 Fayetteville Street, North Carolina 4009 - USA, CA 28309 Tel: 436-320-3968 - Fax 348-370-3915 E-mail:Jeffery_Little@gmail.com
String To Integer Objective C Converter address




String To Integer Objective C Converter


String To Integer Objective C Converter world
{ Read More }


Thursday, 18 May 2017

Counting the number of times pressed of Switch C program in MPLAB X

Counting the number of times pressed of Switch C program in MPLAB X


In this program we are going to count the number of times a switch pressed,and displaying it on a LCD .. and each time the switch pressed a LED will lighted up.




First create a new project and add a c main file like in the  steps for  Blinking a LED using MPLAB X , PIC16F877A

Components 


1. PIC16F877A micro controller
2. animated LED  
3. A toggle switch
4.16x2 LCD display




Steps in the program

1. define the ports for easy usage 

Defines the control pins of LCD to the 0th,1st and 2nd pin of PORT D
    #define RS RD0
    #define RW RD1
   #define EN RD2
Defines the data port of the  LCD to PORT B
   #define DATA PORTC
Defines switch in the 0th pin of PORT C
   #define S RC0
Defines LED on the 3rd pin of PORT D
   #define L RD3
2. Function declarations .. here we declare 3 functions  and all the 3 functions is for LCD

void LCD_CMD(unsigned int value); //This function is pass the LCD commands
void LCD_DAT(unsigned int value); // this is for pass the DATA to the LCD which is to displayed 
void LCD_INIT(); //this to initialize the LCD
void delay(); // this is to delay the LCD commands 

for more refer the    Interfacing LCD with PIC16F877A in MPLAB X

3. next is main function .. in main function we make 
  •  PORT C as input where we have connected the switch
  •  PORT D as output where we have connected the LED and control pins of LCD
  • PORT B as outout where we have connected DATA pins of LCD
    TRISC  =0x0F;
    TRISD  =0x00;
    TRISB = 0x00;

4. The function LCD_INIT(); is called for initializing the LCD
5. Declared a variable called count, and initialized it to zero
   int count;
   count=0;
6.  we put the LED off 
7. now we are going for a infinite loop by 
    while(1)
    { 
     }
8. In the loop we are checking switch is ON or OFF condition
 if the switch is ON ; LED is on and count is incremented by 1 and display the value of count in LCD 

if the Switch is OFF it wait for the condition when the Switch is ON 

schematic diagram 



full Program
 ###################################################################################
    /*
 * File:   switchcount.c
 * Author: Ebin Ephrem
 
 */

#include<htc.h>
__CONFIG(0x193A);

C
#define RS RD0
#define RW RD1
#define EN RD2
#define DATA PORTB
#define S RC0
#define L RD3

void LCD_CMD(unsigned int value);
void LCD_DAT(unsigned int value);
void LCD_INIT();
void delay();



void main(void)
{
    TRISC  =0x0F;
    TRISD  =0x00;
    TRISB = 0x00;
LCD_INIT();
int count;
count=0;
L=0;

  while(1)
  {
if( S == 1)
       {
    while(S==1);
            L= ~L;
                     count = count+1;
              LCD_CMD(0x01);
        delay ();
    LCD_DAT(0 + (count % 10));
}
       }
 }

void LCD_INIT()
 {
    LCD_CMD(0x01);
    delay ();
    LCD_CMD(0x38);
    delay ();
    LCD_CMD(0x0F);
    delay ();
    LCD_CMD(0x06);
    delay ();
    LCD_CMD(0x0c);
    delay ();

    LCD_CMD(0x80);
    delay ();
}
void LCD_CMD(unsigned int  value)
{
    DATA =  value;
    RS=0;
    RW=0;
    EN=1;
    delay ();
    EN=0;
    delay ();
 }

void LCD_DAT(unsigned int value)
{
    DATA= value ;

    RS=1;
    RW=0;
    EN=1;
    delay ();
    EN=0;
    delay();

}

void delay(void)
{
    int counter = 0;
    for (counter = 0; counter<1000; counter++) {
        ;
    }
}





{ Read More }


Monday, 15 May 2017

create child process by fork in linux using C

create child process by fork in linux using C


The tutorial is about to create child process by fork() in linux using C.
fork() which is the library funtion, is used to create child process.I will explain fork() using C.





Now the question is what happens when the child process is created?
When we use fork(), this function splits the running process into two processes, in which one is the parent and other is the child process.

Lets understand this with an example
    this is the C code
  • #include<stdio.h>
    #include<unistd.h>  // for fork()
    void main()
    {  printf("Before calling fork()");
      fork();
      printf("After calling fork()");
    }
  • Output:
    Before calling fork()
    After calling fork()
    After calling fork()

Here, we can see that as the fork() is called the program splitted into
two parallel processes which work simultaneously.


Lets apply our newly learned concept on next level
  • #include<stdio.h>
    #include<unistd.h>
    void main()
    {
      int PID;
      PID=fork();
      if(PID==0)
      {
        //child process
        printf("The pdf files are copying on the Desktop");
      }
      else if(PID>0)
      {
        //parent process
        execl("cp" ,"*.txt" ,"/Desktop" ,NULL);
      }
      else
      printf("Child process isnt created");
      }

NOTE
fork() returns 0 if child process is created
fork() returns PID or process ID of the child process to the parent process.
fork() returns Negative value if child process creation fails.


In above program, child process is displaying the phrase "The pdf files are copying on the Desktop"
and parent process is copying the pdf files.
You can choose the directory according to your system configuration.

Hence guys, this is all about to create child process by fork in linux using C

{ Read More }


Create timer for non windows application in C in which long process is run

Create timer for non windows application in C in which long process is run


There are times when we need to create a timer for our codes, this can be done by following some simple structure like the following:

using System.Threading;

public class WebCrawler
{
private Timer mTimer;

public void Start()
{
mTimer = new Timer(OnTimerTicked, null, 0, 100);
}

public void Stop()
{
mTimer.Change(Timeout.Infinite, Timeout.Infinite);
}

private void OnTimerTicked(object state)
{
DoSomethingLong();
}
}


The problem is the operation implemented in OnTimerTicked may take more than the timer interval (which is 100 milliseconds in the above example) to run. This is not desired as it may lead to memory corruption. The simple way to work around this is to fire the timer only once at the start, which will then invoke OnTimerTicked callback function, at the end of the OnTimerTicked callback, the timer can be reinvoked by calling its change() method, until flag change which cancel the timers ticked operation. This is shown in the following code.

using System.Threading;

public class WebCrawler
{
private Timer mTimer;
private bool mIsWorking;

public void Start()
{
mIsWorking=true;
mTimer = new Timer(OnTimerTicked, null, 0, 100);
}

public void Stop()
{
mIsWorking = false;
mTimer.Change(Timeout.Infinite, Timeout.Infinite);
}

private void OnTimerTicked(object state)
{
if(mIsWorking)
{
DoSomethingLong();
mTimer.Change(100, Timeout.Infinite);
}
}
}

{ Read More }


Sunday, 9 April 2017

Create shared library for C program in Linux

Create shared library for C program in Linux


Consider you c program has two file, which are functions.c and main.c

Consider your current working directory is /home/sujin/shared/

functions.c
int add(int x, int y)
{
    return x + y;
}
 
int sub(int x, int y)
{
        return x - y;
}
 
int mul(int x, int y)
{
        return x * y;
}
 
int div(int x, int y)
{
        return x / y;
}
main.c
#include <stdio.h>
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);
 
int main(int argc, char *argv[])
{
    printf("%d ", add(10, 15));
        printf("%d ", sub(50, 15));
        printf("%d ", mul(10, 3));
        printf("%d ", div(100, 4));
        return 0;
}

1. Compile library source file(functions.c) into position independent code
gcc -c -fpic functions.c -Wall
2. Create shared library from the object file generated
gcc -shared -o libfun.so functions.o 
3. Compile the main program with shared library
gcc -o output main.c -lfun
/usr/bin/ld: cannot find -lfun
collect2: ld returned 1 exit status
4. Compile with giving path of shared library
gcc -L/home/sujin/shared/ -Wall -o output main.c -lfun
5. Run the program
./output 
./output: error while loading shared libraries: libfun.so: cannot open shared object file: No such file or directory
6. Check current LD_LIBRARY_PATH. 
echo $LD_LIBRARY_PATH
7. If LD_LIBRARY_PATH is not current working directory or empty then set the LD_LIBRARY_PATHS as current working directory
LD_LIBRARY_PATH=/home/sujin/shared:$LD_LIBRARY_PATH
8. Run the program
./output 
./output: error while loading shared libraries: libfun.so: cannot open shared object file: No such file or directory
9. Export the LD_LIBRARY_PATH. In linux we need to export the changes in the environment variable
export LD_LIBRARY_PATH=/home/sujin/shared/:$LD_LIBRARY_PATH
10. Run the program
./output
25
35
30
25
{ Read More }