Archive for the ‘gcc’ Category

compilador online

May 11, 2008

http://www.delorie.com/djgpp/compile/

Programando con ncurses

May 3, 2008

Las ncurses son librerías que ayudan a la programación en modo texto para Linux. Es decir, movimientos de cursores, colores, entradas de teclado, sustituyen a conio.h de borland c en otros sistemas, en linux uconio intenta emularla. ncurses es un mayor estado del arte.

Se debe incluir en los programas asi : #include en los programas.
Se compila con: gcc -lncurses fichero.c

En debian debemos instalar el paquete libncurses5-dev con apt-get

#include 

int main() {
initscr();
printw("Hola Mamon!!!");
refresh();
getch();
endwin();
return 0;
}

El popular “hola mundo”

initscr: es para entrar en modo ncurses
printw: es para imprimir en la “ventana”*. Es importante usar printw, scanfw, etc. y no usar printf, scanf, ya que tendríamos resultados no deseados.
refresh: aquí es donde realmente se refresca la pantalla. Podemos hacer varios printw y al final un solo refresh para actualizar la pantalla. Si no hacemos el refresh quizás no saldrá impreso por pantalla.
getch: espera una sola pulsación de una tecla. Nos devuelve el código ASCII de la tecla pulsada como un entero. Fijaros que no espera el “Enter” final de línea
endwin: terminamos el modo de ncurses. Si no lo hacemos, nos quedará el terminal medio desconfigurado. Para solucionarlo podríamos hacer reset desde la misma consola.

Para pedir cosas a un usuario con ncurses (entrada de teclado).

#include 
int main () {
char cadena[128];
initscr();

printw("Dime tu nombre\n");
scanw("%s",cadena);
printw("Te llamas: %s\n",cadena);

refresh();
getch();
endwin();
return(0);
}


Limpiado de pantalla:

        erase();

Posicion del cursor en lugar especifico de pantalla:

        move (10,2);
printw("contraseña: ")

Igualmente podríamos haber usado:

        mvprintw(10,2,"contraseña: ");

Un printw con colores:

        if (has_colors()) {
start_color();

init_pair(1,COLOR_RED,COLOR_YELLOW);
attron(COLOR_PAIR(1));
printw("Escribe la contraseña: ");
attroff(COLOR_PAIR(1));
}

has_colors: devuelve 0 o 1 si el terminal tiene soporte para colores o no.
start_color: inicia el modo de colores. Si no lo hacemos no veremos los colores.
init_pair: asociamos el “par” 1 el color rojo para el texto y el amarillo para el fondo (los colores disponibles con BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE).
attron: y ponemos los colores de forma activa. También podríamos hacer:

        attron(COLOR_PAIR(1) | A_UNDERLINE);

Y así lo tendríamos subrallado. Tenemos disponibles A_NORMAL,A_BLINK, A_BOLD, etc. (man attron para ver más opciones)

Es más, si queremos se pueden personalizar los colores en sí mediante la función init_color (man init_color).


Mas informacion:

ncurses Programming HOWT

FAQ de ncurses

manual de ncurses

Escribir Programas con ncurses (en castellano)

En asterisk por ejemplo necesitamos de estas librerias para poder compilar, incluso las necesitamos si queremos compilar el kernel de linux.

Otra manera de agregar gcc y make a puppy linux

April 3, 2008

Una manera es colocar un sfs module devx_yyy.sfs

Otra manera ingeniosa es descomprimiendo estos archivos en my-applications

Los archivos estan: http://members.lycos.nl/mennoterhaseborg/pupgcc/

Incluyen make, gcc, g77 y as.

Contiki OS: sistema operativo que solo usa 2 MB de RAM

January 7, 2008

Pagina de descarga de un sistema operativo bastante pequeño, especial para sistemas embebidos. Es posible bajar la fuente escrita en C, y luego compilar, se puede usar cygwin para la compilación.

http://www.sics.se/contiki/download.html

Tomado de:http://www.programasfull.com/contiki-un-sistema-operativo-para-maquinas-de-ocho-bits-art1360.html

¿Es usted el poseedor de un Commodore64? ¿o tal vez de una Game Boy? ¿desea dotar a tal aparato de la posibilidad de conectarse a Internet? ¿imposible? ¡no! ahora ya no gracias a Contiki, un sistema operativo de código abierto desarrollado para máquinas de 8 bits. Este sistema operativo no es nuevo, pues ya hace tiempo que podemos encontrarlo en Internet, pero tampoco es antiguo como podría pensarse a simple vista si nos guiamos por el tipo de máquinas a las que va dirigido: antiguas computadoras domésticas como la Atari ST, el Apple ][ o el VIC 20, videoconsolas como la NES (Nintendo Enterainment System) o la Game Boy Advance, o modernos sistemas empotrados en microcontroladores de ocho bits.


El sistema en sí es una pequeña maravilla tecnológica que nos permite exprimir todo el jugo a una arquitectura muerta hace tiempo como es la de los ocho bits, realizando con estas máquinas casi todo lo que puede hacer una moderna computadora de 32 bits.

Su estructura es un kernel básico guiado por eventos (esto es, que responde a eventos o acciones realizadas por los usuarios) con multitarea preemptiva opcional, intercomunicación entre procesos, soporte nativo para TCP/IP y un subsistema gráfico capaz de soportar pantallas conectadas directamente a la máquina o bien trabajar mediante forma remota a través del protocolo VNC. Esto último es así porque Contiki dispone de un servidor VNC integrado en el sistema.

Otras utilidades integradas en el sistema son por ejemplo el servidor web, el navegador y el cliente de Telnet, lo que nos permite montar un completo sistema para navegar por Internet y servir contenidos. Naturalmente, a todo esto hay que sumarle que debemos “buscarnos la vida” para conseguir conectar una máquina como una Game Boy a la Red de redes…

Contiki dispone incluso de una metáfora de escritorio, con sus correspondientes iconos, y una línea de comandos con la que trabajar.

En definitiva, Contiki parece una buena opción si queremos darle una nueva vida a una de estas máquinas de museo, y experimentar la sensación de navegar por Internet o hacer cosas con ella que eran imposibles hace unos años. Porque, imaginen que habría pasado si hubiéramos dispuesto de Contiki y la infraestructura de Internet a principios de los 80…

http://linux.softpedia.com/get/System/Operating-Systems/Other/The-Contiki-Operating-System-25747.shtml

The Contiki Operating System description
The Contiki Operating System is mostly known as an operating system for networked embedded systems. A few years ago, however, Contiki’s primary claim to fame was its Commodore 64 port.

With the help of JAC64, a Java-based C64 emulator developed by my colleague and fellow Contiki developer Joakim Eriksson, you can now experience the C64 port of Contiki 1.2-devel1 again, directly in your web browser!

Como agregar los compiladores en puppy linux (gcc,make, makefile, gcj, etc)…..

November 7, 2007

Ya les comente que puppy linux es una versión minimalista de linux bastante poderosa para maquinas ya algo anticuadas, hoy le he colocado a mi versión 2.14 la posibilidad de poder compilar programas, es decir gcc, make, makefile, etc.

Deben colocar un archivo llamadao devx_214.sfs en el directorio principal donde tengan el archivo pup_save.2fs, si tiene la versión 2.15 entonces deben usar la devx_215.sfs.

En realidad yo me baje la del 2.15 y la renombre, me funciono igual.

El directorio es: /initrd/mnt/dev_save

Estos archivos se los pueden bajar de aqui:

http://puppylinux.org/wikka/Compiling

O de aqui tambien:
http://www.puppyos.net/test/

Aqui les coloco un extracto de la penultima pagina:(cada dia que pasa no deja de sorprenderme puppy linux, en realidad es una excelente distribucion)

To convert Puppy into a complete compiler environment you will need to get the compiling addon file that corresponds with the version of Puppy that you are using, e.g. for Puppy 2.14 devx_214.sfs. So start downloading now, then read while you wait….

Download here:

For most every type of Puppy install (live-cd, frugal), save or copy the file to /mnt/home(if it doesn’t exist then you probably have a full hard drive install, see below). This is where your personal storage file is, e.g. pup_save.2fs or pup001. Now if you’re using Puppy 2.x and haven’t saved your session somewhere then you need to do that first for Puppy to recognize the devx file. Now simply reboot back into Puppy to start compiling.

But for a full/option-2/normal hard drive install to Linux partition with Puppy 2.x, then follow the instructions at the bottom of Barry’s page for now but check back here later for a shortcut.
see also: http://www.murga-linux.com/puppy/viewtopic.php?t=16780

How to Test if devx is installed

Now that you’ve installed you devx module, it is time to test it to see if it works.

Quick Test

Open up rxvt and type ‘cc’ it should spit this back at you
cc: no input files
If it tells you ‘command not found’ then it has not installed properly.

Better Test

Save the following as test.c
If using Geany, set it it to C and test compile first

/* Example C program */

int main()

{ int i;
for (i = 0; i < 50000; i++)
{
printf (“%d”,i);
printf (” Puppy is Great\n);
}
return 0;
}

in the same directory
open a terminal (Right click in the open folder/directory with Rox 2.5 /Window/terminal here)
and type

gcc test.c -o test

this will create a runnable file called “test”
the command

./test

will run it . . .

find a good tutorial e.g.

What does Compiling mean?

In a nutshell: Compiling is the process by which a program written in a human readable format is converted to a computer executable format.
For a full explanation read the Wikipedia: http://en.wikipedia.org/wiki/Compile

compiling…

you can write programs in assembler, which is almost “perfect” in the eyes of a computer, very close to binary code.

lda 02
sta #c000
lda #c001
cmp #c000
bne d000

But this is difficult to understand, in C it might look like this:
a=2;
b=c;
if (a != b){
my_subroutine();
}

This is easier to understand (high-level language), a simple comparison of two numbers, and depending on the result (if they are different), a sub-program is executed.

As computers do not understand “if” and don’t have variables (C) but only a stack (assembler), the code must be translated from C to assembler or even better directly to binary code (assembler itself is not binary, but a very simple form of a “high-level-language” very close to binary code).

This translation is “compiling”.
If you open the resulting “code” in a hexeditor, you will only see binary code, values from 0 to 255 “wildly mixed”. The computer can understand this code, but no human can.

Why Compiling programs

Sometimes you will find that a program or driver that you need or want is not available for Puppy.
The good news is: If that application or driver is open source, you will have access to the source code to compile, but don’t get put off by the long words. These days most open source applications have a very simple way to compile and install from source code.

How to Compile programs

Puppy 2
If you’re running a liveCD or frugal/poor-man’s/option-1/coexist install, stick the devx file in /mnt/home, in the same directory as pup_save.3fs and co.

That’s always been the way to do it with these installations. You only need to put it in root when using an option-2 full-hd install.

Now, if you’ve got a multisession, I don’t know exactly how that works. I imagine the same as the option-2 setup.

If you do have one of the latter two, did you say you were putting it in /root? If so, and that doesn’t work, try / instead. As in the actual root, not /root.


Prerequisites:
The Puppy liveCD does not come with the compilation tools. For that you will need the file devx_201.sfs. [Note that Puppy 2.00 requires devx_200.sfs, Puppy 2.01 requires devx_201.sfs, etc. This is the naming convention for all extra sqaushfs files that allows puppy to recognize them. Puppy 1 versions use usr_devx.sfs, which does not follow this convention.]
The devx_201.sfs is not a standard requirement in Linux. It is just a clever way Barry (Puppy’s creator) found to package all the development tools in an easy to install package. This package includes the tools, libraries and header files required to compile applications.

To install the usr_devx.sfs do the following:
  • Go to this download page and download the devx_201.sfs (http://www.puppyos.com/test/) or (http://www.puppylinux.org/user/downloads.php?cat_id=12)
  • Copy the downloaded file to the same place where your pupxxx.sfs file is located (e.g. pup001.sfs for puppy 1, pup_200.sfs for puppy 2.00, pup_201.sfs for puppy 2.01…). Or in a Hard Drive installation to the / folder. Or in /root on a liveCD.
  • Reboot puppy.
  • or try this explanation


    Puppy has a full gcc make/compile/link suite, available as a scrunched file system. It builds most Linux packages from source using the standard “./configure”, “make”, “make install” incantation.

    The development environments for Puppy 2.00 and 1.xx are available at http://puppylinux.org/user/downloads.php?cat_id=12 . devx_201.sfs is at http://www.puppyos.com/test/ (and at my mirror page: http://s3.amazonaws.com/puppy/index.html )

    To use it, put the devx_xxx.sfs or usr_devx.sfs file in the same place as your pup_save file, and reboot.


    Your application may have other dependencies. Make sure that those dependencies are present in Puppy or that you compile them before trying to compile the application. The ldd command is useful here. Google ‘man ldd linux’. The command is available in Puppy, though the man page is not. As it displays a list of all packages required, and you are probably most interested in just those missing, try
    ldd `which mplayer` |grep not

    Note that the ` on each side of mplayer is a back quotes above the tab button, not regular single quotes. This tells it to run the ldd command on the results of the which command, so you don’t have to first locate mplayer (in this example – replace mplayer with the program you wish to check dependencies for), the results of which are piped through the grep command which only lets through the results containing the word ‘not’
    Example with results:

    ldd `which mplayer` |grep not
    libsmbclient.so.0 => not found

    Of course you could type in

    ldd /etc/local/bin/mplayer

    substituing your app and its path for /etc/local/bin/mplayer, and scan the resulting list manually (thanks for MU, or was it Lobster, who pointed out this simple trick… I like being lazy).

    To Compile:

    • Download source of the application or driver you need:
      It is usually recommended to download the stable version of the package. Only download the development or test versions if you really need them and know what you are doing.
    • Extract source from archive to a suitable location
      Most if not all the applications sources come packaged. Use the appropriate command to extract the source.
      It is Highly advisable to Extract the files to a new or empty folder.
      e.g.
      # mkdir /root/src
      # mkdir /root/src/packageName
      Then download the file to that folder
      # cd /root/src/packageName
      # tar -xvzf packageName.tar.gz
    • READ THE DOCUMENTATION INCLUDED IN THE SOURCE PACKAGE ESPECIALLY ANY INSTALL & README FILES
    • Open a terminal console (e.g. rxvt) and do the following:
      • Change directories to the directory where you extracted the source code e.g. cd /root/src/
      • Follow the compilation instructions included in the source package (README and INSTALL files)

    ….If you run into problems

    1. Remember the INSTALL & README’s ? They usually have addresses of mailing lists you can search
    2. If you do not find the info you are after, try googling
    3. If this fails and you have no ideas make a post to the relevant mailing list
    4. If you get a reply and do not understand or you get no reply post to the puppy forums but please describe EXACTLY the errors you are getting, the version you are trying to compile, the steps you have taken so others may reproduce the same errors then be very very patient
    5. PLEASE DON’T SAY “I CAN’T COMPILE XYZ” “IT DOESN’T WORK” OR ANY OTHER 3 WORD PROBLEM. If you won’t help yourself don’t expect others to do so.
    6. Someone (other than me) make a suggestion that we should mayhaps start a wiki (do the wiki tiki!) on what we can compile in puppy and what we can’t and any possible work arounds.
    7. SelfHostingPuppy


    Optimising

    This little detail is not on the “compiling for puppy” but it’s a fairly important one:

    a lot of Makefiles will leave the “add debug symbol” option of gcc enabled (it’s “-g”). This means that a alot of “text” information is added to your program to facilitate debugging, increasing the program file significanlty.

    When you compile for puppy before typing make (but after the ./configure step if it’s part of the compiling steps) you should open Makefile and look for a line that sets the C flags (usually CFLAGS = ….).

    if the line include -g remove it and see how much space is gained. This will NOT change the behavior of the program.

    There are other optimizations that can be enabled, such as changing the optimizer setting. I find of a lot of program use -O2 by default, changing it to -Os will usually make a smaller program. In theory changing optimizer settings should not change the behavior of your program, however it is possible that it can have subtle side effects that the original programmer didn’t test for.

    I’m really happy to see the source-sorcerer project, because now we can go in and check how each package was built, and make sure that each build is optimized.

    Optimazation options

    Categories

    CategoryDevelopment
    CategoryDocumentation

    ¿Necesito un Compilador de C++ para Windows Vista?

    October 4, 2007

    Con el Dev-C++ en Windows Vista no se compilan las aplicaciones, y el tratar de utilizar el Visual C++ 2005 Express Edition es bastante complicado de utilizar.

    Se puede utilizar el c++ Builder 2007:
    http://btjunkie.org/torrent/CodeGear-RAD…
    y aplicarle este patch
    http://rapidshare.com/files/55765874/bds…

    Eso es todo.


    Follow

    Get every new post delivered to your Inbox.