To divide into .c
and .h
simply create a role in the .h
, and in the .c
put all the code you have. Then it would only be necessary to call on main
. That wouldn’t be a great idea but it would look like this:
matrix. h
#include <stdio.h>
#ifndef MATRIZ_H_INCLUDED
#define MATRIZ_H_INCLUDED
void programa_matriz();
#endif // MATRIZ_H_INCLUDED
matrix. c
#include "matriz.h"
void programa_matriz(){
//todo o código que tinha no main aqui
}
main. c
#include "matriz.c"
int main(){
programa_matriz();
return 0;
}
Split functions by features
One of the ideas of separating into .h
and .c
is able to include the .h
and use the functions you need for each separate feature. This means that it will hardly make sense to "turn a program into a function" but turn each functionality into a function thus giving as much reuse and organization as possible of the code.
In your case you could at least separate into two functions:
- invert matrix
- show matrix
Leaving the creation of matrices in the main
even.
Example:
matrix. h
#include <stdio.h>
#ifndef MATRIZ_H_INCLUDED
#define MATRIZ_H_INCLUDED
void inverter_matriz(int matriz[2][2], int matriz_invertida[2][2]);
void mostrar_matriz(int matriz[2][2]);
#endif // MATRIZ_H_INCLUDED
matrix. c
#include "matriz.h"
void inverter_matriz(int matriz[2][2], int matriz_invertida[2][2]){
int i, j;
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
matriz_invertida[j][i] = matriz[i][j];
}
}
}
void mostrar_matriz(int matriz[2][2]){
int i, j;
for(i = 0; i < 2; i++) {
printf("[ ");
for(j = 0; j < 2; j++) {
printf("%d ", matriz[i][j]);
}
printf("]\n");
}
}
main. c
#include <stdio.h>
#include "matriz.h"
int main(int argc, char *argv[]) {
int matriz_1[2][2];
int matriz_2[2][2];
matriz_1[0][0] = 1;
matriz_1[0][1] = 2;
matriz_1[1][0] = 3;
matriz_1[1][1] = 4;
inverter_matriz(matriz_1, matriz_2);
mostrar_matriz(matriz_2);
return 0;
}
Which operating system is using? Which compiler is using?
– gfleck
I am using Windows 10 and Dev C++ as compiler
– LPd
you have to write the function implementation (the body of the function) into the file . c, the definition in the file .h. http://farside.ph.utexas.edu/teaching/329/lectures/node22.html
– user72726
Got it. Thank you very much!!!
– LPd
Related: https://answall.com/q/306786/64969
– Jefferson Quesado