C静态功能混乱

Lim*_*ime 0 c

我试图只在cord_s.c文件中显示s_cord_print函数.目前,该函数在main.c中是可见/可运行的,即使它被声明为静态.

如何使s_cord_print函数对cord_s.c保密

谢谢!

s_cord.c

typedef struct s_cord{
  int x;
  int y;
  struct s_cord (*print)();
} s_cord;

void* VOID_THIS;
#define $(EL) VOID_THIS=⪙EL

static s_cord s_cord_print(){
  struct s_cord *THIS;
  THIS = VOID_THIS;
  printf("(%d,%d)\n",THIS->x,THIS->y);
  return *THIS;
}

const s_cord s_cord_default = {1,2,s_cord_print};
Run Code Online (Sandbox Code Playgroud)

main.c中

#include <stdio.h>
#include <stdlib.h>

#include "s_cord.c"

int main(){
  s_cord mycord = s_cord_default;
  mycord.x = 2;
  mycord.y = 3;
  $(mycord).print().print();
  //static didn't seem to hide the function
  s_cord_print();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*hen 6

问题是:

#include "s_cord.c"
Run Code Online (Sandbox Code Playgroud)

你应该删除它.而是创建一个s_cord.h仅包含声明的文件,例如:

typedef struct s_cord{
  int x;
  int y;
  struct s_cord (*print)();
} s_cord;
Run Code Online (Sandbox Code Playgroud)

并把:

#include "s_cord.h"
Run Code Online (Sandbox Code Playgroud)

main.cs_cord.c.你还需要一份extern声明s_cord_default.所以完整的代码是:

s_cord.c:

#include "s_cord.h"
#include <stdio.h>

void* VOID_THIS;

static s_cord s_cord_print(){
  struct s_cord *THIS;
  THIS = VOID_THIS;
  printf("(%d,%d)\n",THIS->x,THIS->y);
  return *THIS;
}

const s_cord s_cord_default = {1,2,s_cord_print};
Run Code Online (Sandbox Code Playgroud)

s_cord.h:

typedef struct s_cord{
  int x;
  int y;
  struct s_cord (*print)();
} s_cord;

#define $(EL) VOID_THIS=&EL;EL

extern const s_cord s_cord_default;
extern void *VOID_THIS;
Run Code Online (Sandbox Code Playgroud)

main.c中:

#include <stdio.h>
#include <stdlib.h>

#include "s_cord.h"

int main(){
  s_cord mycord = s_cord_default;
  mycord.x = 2;
  mycord.y = 3;
  $(mycord).print().print();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试s_cord_print()从main 调用,您现在会收到错误,如预期的那样.

编辑:我忘了移动$(EL)定义,它需要一个extern VOID_THIS.

编辑2:正确的编译命令是:

gcc s_cord.c main.c -o main
Run Code Online (Sandbox Code Playgroud)

  • 我建议不要打扰全局的'VOID_THIS`.将对象指针作为参数传递给每个方法.当人们在C中做OO时,这通常是它的工作原理.宏观hackery只是让它看起来很邪恶.(更不用说编写它不是线程安全的,还有其他问题.) (2认同)