I find a difference between C and C++ today. I separated the program in two different files, this is my C test:
/* in file main.c*/
#include <stdio.h>
int main()
{
int a = 3, b = 4;
int c = sum(a, b);
printf("%d\n", c);
}
and
/* In file sum.c */
#include <stdio.h>
int sum(int x, int y)
{
return x + y;
}
then, I compiled them gcc main.c sum.c, no errors and the result is correct. Following is my C++ test, I also separated them in two different files:
/* in file main.cpp*/
#include <iostream>
int main()
{
int a = 3, b = 4;
int c = sum(a, b);
std::cout << c << std::endl;
}
and
/* In file sum.cpp */
#include <iostream>
int sum(int x, int y)
{
return x + y;
}
Compile them g++ main.cpp sum.cpp. An error occurs: error: ‘sum’ was not declared in this scope. If I put a declaration int sum(int, int) in the file main.cpp, then no error occurs. Why there is such a different between C and C++? What's the best way to solve it?
Aucun commentaire:
Enregistrer un commentaire