16.- Curso C++ Básico. Dividir programas en múltiples archivos.

16.- Curso C++ Básico. Dividir programas en múltiples archivos.

Organizing Projects with Multiple Files in Visual Studio

Creating a New Project

  • As programs grow, it's essential to divide them into multiple files for better organization and reusability. Using an ID can simplify working with multiple files.
  • A new console application project named "Maint" is created in Visual Studio. New files are added through the Solution Explorer by right-clicking on the source files folder.

Adding Existing Files

  • Existing files can also be incorporated into the project. If a new file is created directly, it may not automatically add to the open project; this must be done via the Solution Explorer.
  • To add existing files, navigate to Source Files, right-click, select "Add," then "Existing Item," and choose from the default save location.

Managing Project Files

  • Files can be removed from the project using a right-click option. When compiled correctly, all added files should appear in the compiler's list.
  • The tutorial revisits a previous program that failed to compile due to an undefined identifier when calling a function before its definition.

Understanding Compilation Order

  • The function definition for "sumal" is moved from main.cpp to sumal.cpp. The naming of these files does not affect compilation or functionality.
  • Regardless of whether sumar.cpp or main.cpp is compiled first, an error will occur if identifiers are not defined prior to their use.

Compiler Behavior with Multiple Files

  • The compiler processes each file independently without knowledge of other project's contents. It does not retain information about previously compiled code.
  • This limited visibility ensures that functions or variables with identical names across different files do not conflict during compilation.

Resolving Undefined Identifiers

  • Since reordering code isn't feasible due to separate file definitions, forward declarations must be used in main.cpp for unknown identifiers like "sumal."
  • By declaring functions beforehand, the compiler recognizes identifiers during compilation without errors.

Linking Functions Across Files

  • The linker connects calls made in main.cpp to their respective definitions found in other source files within the same project.
Video description

Acceso al AsistenteCPP: https://tinyurl.com/AsistenteCPP. Videotutorial Nº 16 del Curso de C++ Básico en el que vemos como crear proyectos que incluyan más de un archivo .cpp. Vemos como añadir archivos a un proyecto desde Visual Studio y creamos un ejemplo multi-archivo reutilizando un código del videotutorial anterior. Vemos como funciona el compilador cuando analiza un programa con múltiples archivos y porque su visibilidad se limita siempre a un único archivo. Código completo del curso: https://github.com/0utKast/CursoCPPGitHub/archive/refs/heads/master.zip