baicai
baicai

Reputation: 45

call a function from another file in c

I have two files test-subseq.c and maxSeq.c. In test-subseq.c, test_maxSeq calls maxSeq, so I need to add the prototype for maxSeq in test-maxSeq.c so that the compiler knows the function. In maxSeq.c, maxSeq calls max. My question is, in test-maxSeq.c, do I also need to add the prototype for max?

// maxSeq.c 

size_t max(size_t a, size_t b) {
  // returns the larger number between a and b
}

size_t maxSeq(int * array, size_t n) {
  /* 
   * returns the length of the maximum increasing contiguous subsequence
   * in the array and call max
   */
}
// test-subseq.c

size_t maxSeq(int * array, size_t n);

void test_maxSeq(int * array, size_t n, size_t expt) {
  size_t ans = maxSeq(array, n);
  assert(ans == expt)
}

int main(void) {
  int array0 = {1, 2, 1, 3, 5, 7};
  test_maxSeq(array0, 6, 4);
  return 0;
}

Upvotes: 1

Views: 92

Answers (2)

m.18
m.18

Reputation: 70

Put maxSeq in a header file and then include the header file in test-subseq.c

Upvotes: 1

Daniel Walker
Daniel Walker

Reputation: 6772

No, test-subseq.c only needs declarations for the functions which it will specifically call.

However, as the commenter said, it's better practice to put your declarations in a header file and #include that in test-subseq.c.

Upvotes: 2

Related Questions