Blob Blame History Raw
<?xml version="1.0" encoding="utf-8"?>
<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" type="topic" id="c-coding-style" xml:lang="es">

  <info>
    <link type="guide" xref="index#general-guidelines"/>

    <credit type="author copyright">
      <name>Federico Mena-Quintero</name>
      <email its:translate="no">federico@gnome.org</email>
      <years>2013</years>
    </credit>
    <credit type="author copyright">
      <name>El equipo de GTK+</name>
    </credit>

    <include xmlns="http://www.w3.org/2001/XInclude" href="cc-by-sa-3-0.xml"/>

    <desc>Nuestras directrices para el código C en GNOME</desc>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Daniel Mustieles</mal:name>
      <mal:email>daniel.mustieles@gmail.com</mal:email>
      <mal:years>2016</mal:years>
    </mal:credit>
  
    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
      <mal:name>Javier Mazorra</mal:name>
      <mal:email>mazi.debian@gmail.com</mal:email>
      <mal:years>2016</mal:years>
    </mal:credit>
  </info>

  <title>Estilo de codificación en C</title>

  <p>Este documento presenta el estilo de codificación preferido para los programas en C en GNOME. Mientras que el estilo de codificación es en gran medida una cuestión de gustos, en GNOME estamos a favor de un estilo de codificación que promueve la consistencia, legibilidad y mantenibilidad.</p>

  <p>Presentamos ejemplos de buen estilo de codificación así como ejemplos de mal estilo que no es aceptable en GNOME. Intente enviar parches que se ajusten al estilo de codificación de GNOME; esto indica que ha hecho sus deberes respecto al objetivo del proyecto de mantenibilidad a largo plazo. ¡Los parches con el estilo de codificación de GNOME serán también más fáciles de revisar!</p>

  <note>
    <p>Este documento es para código C. Para otros lenguajes, compruebe la <link xref="índex">página principal</link> de las directrices de programación de GNOME.</p>
  </note>

  <p>Estas directrices están fuertemente inspiradas por el documento GTK’s CODING STYLE, el Linux Kernel’s CodingStyle, y el GNU Coding Standards. Estos son pequeñas variaciones cada uno de otro, con modificaciones particulares para las necesidades y cultura particulares de cada proyecto, y la versión de GNOME no es diferente.</p>

  <section id="most-important-rule">
    <title>La única regla más importante</title>

    <p>La única regla más importante al escribir código es: <em>revise el código existente y trate de imitarlo</em>.</p>

    <p>Como mantenedor es desalentador recibir un parche que está obviamente en un estilo de codificación diferente al código ya existente. Esto es una falta de respeto, como cuando alguien pisa en una casa impecablemente limpia con los zapatos llenos de barro.</p>

    <p>Por lo tanto, sea lo que sea lo que este documento recomienda, si ya hay código y lo está parcheando, mantenga su estilo actual coherente incluso si no es su estilo favorito.</p>
  </section>

  <section id="line-width">
    <title>Anchura de línea</title>

    <p>Intente usar líneas de código de entre 80 y 120 caracteres de largo. Esta cantidad de texto es fácil de ajustar en la mayoría de monitores con un tamaño de tipografía decente. Las líneas más largas se vuelve difíciles de leer, y significan que probablemente debería reestructurar su código. Si tiene demasiados niveles de sangrado, significa que debería arreglar su código de alguna manera.</p>
  </section>

  <section id="indentation">
    <title>Sangrado</title>

    <p>En general hay dos estilos de sangrado preferidos para el código en GNOME.</p>

    <list type="ordered">
      <item>
	<p>Estilo del kernel de Linux. Los tabuladores con una longitud de 8 caracteres se usan para el sangrado, con K&amp;R el lugar de las llaves:</p>

	<code style="valid">
for (i = 0; i &lt; num_elements; i++) {
	foo[i] = foo[i] + 42;

	if (foo[i] &lt; 35) {
		printf ("Foo!");
		foo[i]--;
	} else {
		printf ("Bar!");
		foo[i]++;
	}
}</code>
      </item>

      <item>
	<p>Estilo GNU. Cada nuevo nivel se sangra con dos espacios, las llaves van en una línea solas, y se sangran también.</p>

	<code style="valid">
for (i = 0; i &lt; num_elements; i++)
  {
    foo[i] = foo[i] + 42;

    if (foo[i] &lt; 35)
      {
        printf ("Foo!");
        foo[i]--;
      }
    else
      {
        printf ("Bar!");
        foo[i]++;
      }
  }</code>
      </item>
    </list>


    <p>Ambos estilos tienen sus pros y contras. Lo más importante es <em>ser coherente</em> con el código existente. Por ejemplo, la biblioteca GTK+, que es el kit de herramientas para widgets de GNOME, está escrita con el estilo GNU. Nautilus, el gestor de archivos de GNOME, está escrito con el estilo del kernel de Linux. Ambos estilos son perfectamente legibles y coherentes cuando se acostumbra a ellos.</p>

    <p>
      Your first feeling when having to study or work on a piece of
      code that doesn’t have your preferred indentation style may be,
      how shall we put it, gut-wrenching.  You should resist your
      inclination to reindent everything, or to use an inconsistent
      style for your patch.  Remember the first rule:  <em>be
      consistent</em> and respectful of that code’s customs, and your
      patches will have a much higher chance of being accepted without
      a lot of arguing about the right indentation style.
    </p>
  </section>

  <section id="tab-characters">
    <title>Tabuladores</title>

    <p><em>Nunca cambie el tamaño de los tabuladores en su editor</em>; déjelos con 8 espacios. Cambiar el tamaño de los tabuladores significa que el código que no escribió estará perpetuamente mal alineado.</p>

    <p>
      Instead, set the <em>indentation size</em> as appropriate for
      the code you are editing.  When writing in something other than
      Linux kernel style, you may even want to tell your editor to
      automatically convert all tabs to 8 spaces, so that there is no
      ambiguity about the intended amount of space.
    </p>
  </section>

  <section id="braces">
    <title>Paréntesis</title>

    <p>Las llaves no deberían usarse para bloques de una sola sentencia:</p>

<code style="valid">
/* valid */
if (condition)
	single_statement ();
else
	another_single_statement (arg1);</code>

	<p>
	  The “no block for single statements” rule has only four
	  exceptions:
	</p>

	<list type="ordered">
          <item>
            <p>
              In GNU style, if either side of an if-else statement has
              braces, both sides should, to match up indentation:
            </p>

<code style="valid">
/* valid GNU style */
if (condition)
  {
    foo ();
    bar ();
  }
else
  {
    baz ();
  }</code>

<code style="invalid">
/* invalid */
if (condition)
  {
    foo ();
    bar ();
  }
else
  baz ();</code>
          </item>

	  <item>
	    <p>
	      If the single statement covers multiple lines, e.g. for functions with
	      many arguments, and it is followed by <code>else</code> or
	      <code>else if</code>:
	    </p>

<code style="valid">
/* valid Linux kernel style */
if (condition) {
	a_single_statement_with_many_arguments (some_lengthy_argument,
						another_lengthy_argument,
						and_another_one,
						plus_one);
} else
	another_single_statement (arg1, arg2);

/* valid GNU style */
if (condition)
  {
    a_single_statement_with_many_arguments (some_lengthy_argument,
                                            another_lengthy_argument,
                                            and_another_one,
                                            plus_one);
  }
else
  {
    another_single_statement (arg1, arg2);
  }</code>
          </item>

          <item>
            <p>Si la condición se compone de varias líneas:</p>

<code style="valid">
/* valid Linux kernel style */
if (condition1 ||
    (condition2 &amp;&amp; condition3) ||
    condition4 ||
    (condition5 &amp;&amp; (condition6 || condition7))) {
	a_single_statement ();
}

/* valid GNU style */
if (condition1 ||
    (condition2 &amp;&amp; condition3) ||
    condition4 ||
    (condition5 &amp;&amp; (condition6 || condition7)))
  {
    a_single_statement ();
  }</code>

            <p>
              Note that such long conditions are usually hard to understand.  A
              good practice is to set the condition to a boolean variable, with
              a good name for that variable.  Another way is to move the long
              condition to a function.
            </p>
          </item>

          <item>
            <p>
              Nested <code>if</code>s, in which case the block should be placed
              on the outermost <code>if</code>:
            </p>

<code style="valid">
/* valid Linux kernel style */
if (condition) {
	if (another_condition)
		single_statement ();
	else
		another_single_statement ();
}

/* valid GNU style */
if (condition)
  {
    if (another_condition)
      single_statement ();
    else
      another_single_statement ();
  }</code>

<code style="invalid">
/* invalid */
if (condition)
	if (another_condition)
		single_statement ();
	else if (yet_another_condition)
		another_single_statement ();</code>
          </item>
        </list>

        <p>En general, los bloques nuevos se deben colocar con un nivel de sangrado nuevo, como esto:</p>

        <code style="valid">
int retval = 0;

statement_1 ();
statement_2 ();

{
	int var1 = 42;
	gboolean res = FALSE;

	res = statement_3 (var1);

	retval = res ? -1 : 1;
}</code>

        <p>
          While curly braces for function definitions should rest on a
          new line they should not add an indentation level:
        </p>

        <code style="valid">
/* valid Linux kernel style*/
static void
my_function (int argument)
{
	do_my_things ();
}

/* valid GNU style*/
static void
my_function (int argument)
{
  do_my_things ();
}</code>

<code style="invalid">
/* invalid */
static void
my_function (int argument) {
	do_my_things ();
}

/* invalid */
static void
my_function (int argument)
  {
    do_my_things ();
  }</code>
  </section>

  <section id="conditions">
    <title>Condiciones</title>

    <p>
      Do not check boolean values for equality.  By using implicit
      comparisons, the resulting code can be read more like conversational
      English.  Another rationale is that a ‘true’ value may not be necessarily
      equal to whatever the <code>TRUE</code> macro uses.  For example:
    </p>

    <code style="invalid">
/* invalid */
if (found == TRUE)
	do_foo ();

/* invalid */
if (found == FALSE)
	do_bar ();</code>

    <code style="valid">
/* valid */
if (found)
	do_foo ();

/* valid */
if (!found)
	do_bar ();</code>

    <p>
      The C language uses the value 0 for many purposes.  As a numeric value,
      the end of a string, a null pointer and the <code>FALSE</code> boolean.
      To make the code clearer, you should write code that highlights the
      specific way 0 is used.  So when reading a comparison, it is possible to
      know the variable type.  For boolean variables, an implicit comparison is
      appropriate because it’s already a logical expression.  Other variable
      types are not logical expressions by themselves, so an explicit
      comparison is better:
    </p>

    <code style="valid">
/* valid */
if (some_pointer == NULL)
	do_blah ();

/* valid */
if (number == 0)
	do_foo ();

/* valid */
if (str != NULL &amp;&amp; *str != '\0')
	do_bar ();</code>

    <code style="invalid">
/* invalid */
if (!some_pointer)
	do_blah ();

/* invalid */
if (!number)
	do_foo ();

/* invalid */
if (str &amp;&amp; *str)
	do_bar ();</code>
  </section>

  <section id="functions">
    <title>Funciones</title>

    <p>Las funciones se deben declarar colocando el valor devuelto en una línea separada del nombre de la función:</p>

    <code style="valid">
void
my_function (void)
{
  …
}</code>

    <p>
      The argument list must be broken into a new line for each
      argument, with the argument names right aligned, taking into
      account pointers:
    </p>

    <code style="valid">
void
my_function (some_type_t      type,
             another_type_t  *a_pointer,
             double_ptr_t   **double_pointer,
             final_type_t     another_type)
{
  …
}</code>

    <p>
      If you use Emacs, you can use <code>M-x align</code> to do this
      kind of alignment automatically.  Just put the point and mark
      around the function’s prototype, and invoke that command.
    </p>

    <p>
      The alignment also holds when invoking a function without breaking the
      line length limit:
    </p>

    <code style="valid">
alinear_argumentos_funciones (primer_argumento,
                          segundo_argumento,
                          tercer_argumento);</code>
  </section>

  <section id="whitespace">
    <title>Espacio en blanco</title>

    <p>Ponga siempre un espacio antes de abrir un paréntesis, pero nunca después:</p>

    <code style="valid">
/* valid */
if (condition)
	do_my_things ();

/* valid */
switch (condition) {
}</code>

<code style="invalid">
/* invalid */
if(condition)
	do_my_things();

/* invalid */
if ( condition )
	do_my_things ( );</code>

    <p>
      When declaring a structure type use newlines to separate logical sections
      of the structure:
    </p>

    <code style="valid">
struct _GtkWrapBoxPrivate
{
	GtkOrientation        orientation;
	GtkWrapAllocationMode mode;

	GtkWrapBoxSpreading   horizontal_spreading;
	GtkWrapBoxSpreading   vertical_spreading;

	guint16               vertical_spacing;
	guint16               horizontal_spacing;

	guint16               minimum_line_children;
	guint16               natural_line_children;

	GList                *children;
};</code>

    <p>No elimine espacios en blanco y saltos de línea simplemente porque algo quepa en una única línea:</p>

    <code style="invalid">
/* invalid */
if (condition) foo (); else bar ();</code>

    <p>
      Do eliminate trailing whitespace on any line, preferably as a separate
      patch or commit. Never use empty lines at the beginning or at the end of
      a file.
    </p>

    <p>
      This is a little Emacs function that you can use to clean up
      lines with trailing whitespace:
    </p>

    <code>
(defun clean-line-ends ()
  (interactive)
  (if (not buffer-read-only)
      (save-excursion
	(goto-char (point-min))
	(let ((count 0))
	  (while (re-search-forward "[ 	]+$" nil t)
	    (setq count (+ count 1))
	    (replace-match "" t t))
	  (message "Cleaned %d lines" count)))))</code>
  </section>

  <section id="switch">
    <title>La sentencia <code>switch</code></title>

    <p>
      A <code>switch</code> should open a block on a new
      indentation level, and each <code>case</code> should start on
      the same indentation level as the curly braces, with the case
      block on a new indentation level:
    </p>

    <code style="valid">
/* valid Linux kernel style */
switch (condition) {
case FOO:
	do_foo ();
	break;

case BAR:
	do_bar ();
	break;
}

/* valid GNU style */
switch (condition)
  {
  case FOO:
    do_foo ();
    break;

  case BAR:
    do_bar ();
    break;
  }</code>

<code style="invalid">
/* invalid */
switch (condition) {
  case FOO: do_foo (); break;
  case BAR: do_bar (); break;
}

/* invalid */
switch (condition)
  {
  case FOO: do_foo ();
    break;
  case BAR: do_bar ();
    break;
  }

/* invalid */
switch (condition)
  {
    case FOO:
    do_foo ();
    break;
    case BAR:
    do_bar ();
    break;
  }</code>

    <p>Es preferible, pero no obligatorio, separar los distintos casos con un salto de línea:</p>

    <code style="valid">
switch (condition) {
case FOO:
	do_foo ();
	break;

case BAR:
	do_bar ();
	break;

default:
	do_default ();
}</code>

    <p>La sentencia <code>break</code> para el caso <code>default</code> no es obligatoria.</p>

    <p>
      If switching over an enumerated type, a <code>case</code> statement must
      exist for every member of the enumerated type. For members you do not
      want to handle, alias their <code>case</code> statements to
      <code>default</code>:
    </p>

    <code style="valid">
switch (enumerated_condition) {
case HANDLED_1:
	do_foo ();
	break;

case HANDLED_2:
	do_bar ();
	break;

case IGNORED_1:
case IGNORED_2:
default:
	do_default ();
}</code>

    <p>
      If most members of the enumerated type should not be handled, consider
      using an <code>if</code> statement instead of a <code>switch</code>.
    </p>

    <p>
      If a <code>case</code> block needs to declare new variables, the same rules as the
      inner blocks apply (see above); the <code>break</code> statement should be placed
      outside of the inner block:
    </p>

    <code style="valid">
/* valid GNU style */
switch (condition)
  {
  case FOO:
    {
      int foo;

      foo = do_foo ();
    }
    break;

  …
  }</code>
  </section>

  <section id="header-files">
    <title>Archivos de cabecera</title>

    <p>
      The only major rule for headers is that the function definitions
      should be vertically aligned in three columns:
    </p>

    <code style="valid">
return_type          function_name           (type   argument,
                                              type   argument,
                                              type   argument);</code>

    <p>La anchura máxima de cada columna viene dada por el elemento más largo de la columna:</p>

    <code style="valid">
void         gtk_type_set_property (GtkType      *type,
                                    const gchar  *value,
                                    GError      **error);
const gchar *gtk_type_get_property (GtkType      *type);</code>

    <p>También es posible alinear las columnas al siguiente tabulador:</p>

    <code style="valid">
void          gtk_type_set_prop           (GtkType *type,
                                           gfloat   value);
gfloat        gtk_type_get_prop           (GtkType *type);
gint          gtk_type_update_foobar      (GtkType *type);</code>

    <p>
      As before, you can use <code>M-x align</code> in Emacs to do
      this automatically.
    </p>

    <p>
      If you are creating a public library, try to export a single
      public header file that in turn includes all the smaller header
      files into it.  This is so that public headers are never
      included directly; rather a single include is used in
      applications.  For example, GTK+ uses the following in its
      header files that should not be included directly by
      applications:
    </p>

    <code style="valid">
#if !defined (__GTK_H_INSIDE__) &amp;&amp; !defined (GTK_COMPILATION)
#error "Only &lt;gtk/gtk.h&gt; can be included directly."
#endif</code>

    <p>
      For libraries, all headers should have inclusion guards (for
      internal usage) and C++ guards.  These provide the <code>extern
      "C"</code> magic that C++ requires to include plain C headers:
    </p>

    <code style="valid">
#ifndef MYLIB_FOO_H_
#define MYLIB_FOO_H_

#include &lt;gtk/gtk.h&gt;

G_BEGIN_DECLS

…

G_END_DECLS

#endif /* MYLIB_FOO_H_ */</code>
  </section>

  <section id="gobject">
    <title>Clases de GObject</title>

    <p>
      GObject class definitions and implementations require some
      additional coding style notices, and should always be
      <link xref="namespacing#gobject">correctly namespaced</link>.
    </p>

    <p>Las declaraciones «typedef» se deben colocar al principio del archivo.</p>

    <code style="valid">
typedef struct _GtkBoxedStruct       GtkBoxedStruct;
typedef struct _GtkMoreBoxedStruct   GtkMoreBoxedStruct;</code>

    <p>Esto incluye los tipos enumerados:</p>

    <code style="valid">
typedef enum
{
  GTK_SIZE_REQUEST_WIDTH_FOR_HEIGHT,
  GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH
} GtkSizeRequestMode;</code>

    <p>Y los tipos de retornos de llamadas:</p>

    <code style="valid">
typedef void (* GtkCallback) (GtkWidget *widget,
                              gpointer   user_data);</code>

    <p>Las instancias de estructuras se deben declarar usando <code>G_DECLARE_FINAL_TYPE</code> o <code>G_DECLARE_DERIVABLE_TYPE</code>:</p>

    <code style="valid">
#define GTK_TYPE_FOO (gtk_foo_get_type ())
G_DECLARE_FINAL_TYPE (GtkFoo, gtk_foo, GTK, FOO, GtkWidget)</code>

    <p>
      For final types, private data can be stored in the object struct, which
      should be defined in the C file:
    </p>

    <code style="valid">
struct _GtkFoo
{
  GObject   parent_instance;

  guint     private_data;
  gpointer  more_private_data;
};</code>

    <p>
      For derivable types, private data must be stored in a private struct in
      the C file, configured using <code>G_DEFINE_TYPE_WITH_PRIVATE()</code>
      and accessed using a <code>_get_instance_private()</code> function:
    </p>

    <code style="valid">
#define GTK_TYPE_FOO gtk_foo_get_type ()
G_DECLARE_DERIVABLE_TYPE (GtkFoo, gtk_foo, GTK, FOO, GtkWidget)

struct _GtkFooClass
{
  GtkWidgetClass parent_class;

  void (* handle_frob)  (GtkFrobber *frobber,
                         guint       n_frobs);

  gpointer padding[12];
};</code>

    <p>
      Always use the <code>G_DEFINE_TYPE()</code>,
      <code>G_DEFINE_TYPE_WITH_PRIVATE()</code>, and
      <code>G_DEFINE_TYPE_WITH_CODE()</code> macros, or their abstract variants
      <code>G_DEFINE_ABSTRACT_TYPE()</code>,
      <code>G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE()</code>,
      and <code>G_DEFINE_ABSTRACT_TYPE_WITH_CODE()</code>; also, use the similar
      macros for defining interfaces and boxed types.
    </p>

    <p>
      Interface types should always have the dummy typedef for cast
      purposes:
    </p>

    <code style="valid">
typedef struct _GtkFooable          GtkFooable;</code>

    <p>
      The interface structure should have ‘Interface’ postfixed to the
      dummy typedef:
    </p>

    <code style="valid">
typedef struct _GtkFooableInterface     GtkFooableInterface;</code>

    <p>Las interfaces deben tener las siguientes macros:</p>

    <table>
      <thead>
	<tr>
	  <td><p>Macro</p></td>
	  <td><p>Se expande a</p></td>
	</tr>
      </thead>
      <tbody>
	<tr>
	  <td><p><code>GTK_TYPE_<var>iface_name</var></code></p></td>
	  <td><p><code><var>iface_name</var>_get_type</code></p></td>
	</tr>
	<tr>
	  <td><p><code>GTK_<var>iface_name</var></code></p></td>
	  <td><p><code>G_TYPE_CHECK_INSTANCE_CAST</code></p></td>
	</tr>
	<tr>
	  <td><p><code>GTK_IS_<var>iface_name</var></code></p></td>
          <td><p><code>G_TYPE_CHECK_INSTANCE_TYPE</code></p></td>
	</tr>
	<tr>
	  <td><p><code>GTK_<var>iface_name</var>_GET_IFACE</code></p></td>
          <td><p><code>G_TYPE_INSTANCE_GET_INTERFACE</code></p></td>
	</tr>
      </tbody>
    </table>

  </section>

  <section id="memory-allocation">
    <title>Reserva de memoria</title>

    <p>
      When dynamically allocating data on the heap use <code>g_new()</code>.
    </p>

    <p>
      Public structure types should always be returned after being
      zero-ed, either explicitly for each member, or by using
      <code>g_new0()</code>.
    </p>

    <p>Consulte la <link xref="memory-management"/> para obtener más detalles.</p>
  </section>

  <section id="macros">
    <title>Macros</title>

    <p>
      Try to avoid private macros unless strictly necessary. Remember
      to <code>#undef</code> them at the end of a block or a series of functions
      needing them.
    </p>

    <p>Normalmente, se prefieren las funciones en línea a las macros privadas</p>

    <p>
      Public macros should not be used unless they evaluate to a
      constant.
    </p>
  </section>

  <section id="public-api">
    <title>API pública</title>

    <p>
      Avoid exporting variables as public API, since this is
      cumbersome on some platforms. It is always preferable to add
      getters and setters instead.  Also, beware global variables in
      general.
    </p>
  </section>

  <section id="private-api">
    <title>API privada</title>

    <p>
      Non-exported functions that are needed in more than one source file
      should be prefixed with an underscore (‘_’), and declared in a
      private header file.  For example, <code>_mylib_internal_foo()</code>.
    </p>

    <p>Las funciones con un guión bajo al principio nunca se exportan.</p>

    <p>
      Non-exported functions that are only needed in one source file
      should be declared static.
    </p>
  </section>
</page>