I'm just starting to teach C++, coming from some other languages. I am wishing there were some way to consistently check the API created by a (student) file.
Suppose a student submits this file:
// this is stu.cpp
#include <iostream>
using namespace std;
double x(int y) {return y+0.5;}
Actually, suppose I asked the student to define some other function int x(int). I would like to be able to check this by running this code:
// this is stu.h
int x(int);
// this is gra.cpp
#include "stu.h"
#include <iostream>
using namespace std;
int main() {
cout << x(0); // test their code
}
So I am trying to see if the student's implementation matched the required interface, and testing it on input 0. I would have hoped this would not compile. But when I do
g++ -Wall -Wconversion *.cpp -o gra
./gra
It compiles and runs without crashing, giving output 0. This remains true even if I compile the two files separately and link them after.
I know that nm
doesn't list return types. Is that the same reason that we can link together two files when the return values don't match? Is there any sane way to test this? (Like are there compile-time typeof assertions?)
Or is this a specific bug because of int and double being interconvertible? Are there additionall compiler options that could catch this?
Instead of compiling the student's code separately, why don't you just include it directly in your tester program?
int x(int);
#include <stu.cpp>
Then you should get a nice error like this:
a.cpp:2:8: error: functions that differ only in their return type cannot be overloaded
While this is not the "normal" way to compile a student's code, it guarantees that the code can be checked.
Alternatively, you may use a compiler command-line option like -include
(GCC, Clang) to force the compiler to include a header file containing your desired API when compiling the student's C++ file. As an example:
api.h
int x(int);
compile with g++ stu.cpp -include api.h
, and the appropriate error will be raised.
You can do the following:
// this is gra.cpp
#include "stu.h"
#include "stu.cpp"
#include <iostream>
using namespace std;
int main() {
cout << x(0); // test their code
}
And compile only gra.cpp
of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With