Tuesday, August 23, 2016

How to call a function before the main function and after 'return 0' line

Some applications needs to call a function before the main function takes the control for loading a specific value form somewhere or after the program dies for saving settings or something like that but, how?

Its very simple.

__attribute__

This peace of code has two options or two parameters to pass.
If constructor is passed, the function will be executed before the main function.
Unlike, if destructor is passed, the function will be executed after int main returns 0

Examples :


1- Executing before main function


#include iostream
using namespace std;

void beforemain(void)__attribute__((constructor));

void beforemain(void)
  {
     cout<<"hi befor main\n";
  }
           
int main()
  {
      cout<<"main\n";
      return 0;
  }


2- Executing after closing the program


#include iostream
using namespace std;

void aftermain(void)__attribute__((destructor));

void aftermain(void)
   {
        cout<<"bye after main\n";
   }
          
int main()
   {
        cout<<"main\n";
        return 0;
    }

Pretty easy and straightforward, right !

Friday, August 12, 2016

Introduction to computer programming

Before getting to computer programming, lets first understand computer programs and what they do.

A computer program is a sequence of instructions written using a programming language and converted to the machine language to do a specific task.

You can consider that a programming language converts your logic into the computer logic
If somebody asks you how to login to facebook your answer will be like : 

 Open facebook, create account then login

Now, try to arrange your answer in sequence and you will get :

 1 - Open facebook
 2 - Create account  
 3 - Login

Actually, you can consider this sequence as a computer program written in your original language.

Now, lets talk about programming again. A computer program is a sequence of instruction tells the computer what to do.
For example, This C code tells the computer to prints "Hello World!" on the screen.

printf("Hello Wordl!");

Introduction to computer programming.

If you understood what a computer program is then you will answer yourself "Writing a computer program is computer programming"
You are right, but how. As we mentioned, the computer can't understand what you say and you have to convert your instructions that You need him to do into machine language.
For this purpose, the computer programming languages are invented.
There are many programming languages such as
  • Assembly
  • C
  • C++
  • Java
  • Python
  • C#
  • Perl
  • VB.NET
And many more.

This is just an introduction to the world of programming, other guides on how to be a programmer will be posted soon.