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.cpptosumal.cpp. The naming of these files does not affect compilation or functionality.
- Regardless of whether
sumar.cppormain.cppis 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.cppfor 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.cppto their respective definitions found in other source files within the same project.